<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yashara Induwara on Medium]]></title>
        <description><![CDATA[Stories by Yashara Induwara on Medium]]></description>
        <link>https://medium.com/@yasharainduwara?source=rss-2ff90c913782------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EQsjZNIb_c724ES-xfr8Rw.png</url>
            <title>Stories by Yashara Induwara on Medium</title>
            <link>https://medium.com/@yasharainduwara?source=rss-2ff90c913782------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:06:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasharainduwara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deadlocks Over Rows That Don’t Exist]]></title>
            <link>https://yasharainduwara.medium.com/deadlocks-over-rows-that-dont-exist-2b401f34cfa8?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b401f34cfa8</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-engineering]]></category>
            <category><![CDATA[innodb]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 02:36:01 GMT</pubDate>
            <atom:updated>2026-12-03T02:36:01.640Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MySQL Under Pressure, Part 5 - gap locks, next-key locks and what performance_schema.data_locks tells you</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEZhuC7tQl_8LXrLc3sizg.jpeg" /></figure><p>Some of the most confusing deadlocks are the ones where nothing obviously conflicts. Two sessions each check that a row doesn’t exist, find nothing, try to insert different rows, and one of them gets ERROR 1213: Deadlock found. They never touched the same row. In fact, there was no row to touch.</p><p>I wanted to understand those deadlocks well enough to predict them, so I reproduced them one lock at a time on MySQL 8.0.46. I captured performance_schema.data_locks after every statement, mapped exactly which inserts a range UPDATE blocks, and then ran common upsert patterns under concurrency to count how often each one deadlocks.</p><p>As in <a href="https://yasharainduwara.medium.com/i-crashed-mysql-31-times-to-see-what-it-really-loses-378a40281221">part 1</a> through part 4, the scripts and raw output are linked at the end, and I say plainly where I’m reasoning beyond what I measured.</p><p><strong>The short version</strong></p><ul><li>The classic check-then-insert pattern (SELECT ... FOR UPDATE, then INSERT if nothing came back) deadlocked in both of my scripted runs where two sessions checked keys in the same gap under REPEATABLE READ, even for different keys. Under 8 threads of insert-heavy traffic, it deadlocked 5.6–8.3 times per 10,000 attempts.</li><li>The same code under READ COMMITTED didn&#39;t deadlock at all, and neither did INSERT ... ON DUPLICATE KEY UPDATE under either isolation level. The upsert also did twice the throughput.</li><li>UPDATE ... WHERE k BETWEEN 30 AND 50 on an indexed column also locked a row with k = 60 that it didn&#39;t match. On an unindexed column, an UPDATE that matched <strong>zero rows</strong> blocked every insert into the table.</li><li>READ COMMITTED didn&#39;t make deadlocks impossible. The manual&#39;s three-session duplicate-key deadlock reproduced under both isolation levels.</li><li>data_locks has a trap: during a duplicate-key check, a lock that belongs to one transaction was recorded against another session&#39;s thread. Join it on ENGINE_TRANSACTION_ID, not THREAD_ID.</li></ul><h3>Four kinds of lock, briefly</h3><p>InnoDB doesn’t only lock rows. It locks positions in an index, and four kinds of lock explain everything in this post. All four are defined in the manual’s <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html">InnoDB Locking</a> page.</p><ul><li><strong>Record lock:</strong> a lock on one index record.</li><li><strong>Gap lock:</strong> a lock on the gap between two index records. Its only purpose is to stop other transactions inserting into that gap.</li><li><strong>Next-key lock:</strong> a record lock plus a gap lock on the gap before that record.</li><li><strong>Insert intention lock:</strong> a special gap lock that an INSERT takes on the gap it&#39;s inserting into.</li></ul><p>Two properties of gap locks cause most of the surprises. First, gap locks don’t conflict with each other. Two transactions can hold a gap lock on the same gap at the same time. Second, an insert intention lock <em>does</em> conflict with a gap lock held by someone else. So two transactions can both lock a gap, and then neither can insert into it.</p><p>By default InnoDB runs at REPEATABLE READ and uses next-key locks for searches and index scans, which is how it prevents phantom rows. Under READ COMMITTED, gap locking is disabled for searches and index scans, and is used only for foreign-key and duplicate-key checking.</p><p>The <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html">Locks Set by Different SQL Statements</a> page adds two rules that matter here. A locking read, UPDATE or DELETE locks every index record it scans, whether or not the WHERE clause would exclude the row. And if there&#39;s no suitable index, every row of the table gets locked.</p><h3>How I tested it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*I-OXsz0_zU1OCD0HgcEikg.png" /></figure><p>In the scenarios, the lock tables show which session holds what at each moment. In the benchmark, every error is counted by code: 1213 (deadlock), 1205 (lock wait timeout) and 1062 (duplicate key). As a cross-check, I compared my deadlock count with InnoDB’s own lock_deadlocks counter in information_schema.INNODB_METRICS. They matched in every run.</p><h3>Experiment 1: check-then-insert</h3><p>This is the pattern behind countless “get or create” functions: lock the key if it exists, insert it if it doesn’t.</p><pre>-- Session A                               -- Session B<br>BEGIN;                                     BEGIN;<br>SELECT * FROM t WHERE id = 25 FOR UPDATE;<br>                                           SELECT * FROM t WHERE id = 27 FOR UPDATE;<br>INSERT INTO t VALUES (25, 25, 0);  -- waits<br>                                           INSERT INTO t VALUES (27, 27, 0);  -- ERROR 1213</pre><p>Neither 25 nor 27 exists; the table holds 10, 20, 30 and so on. Here is data_locks after both SELECT ... FOR UPDATE statements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*DfrOgB_uoVsNHTohKlLVog.png" /></figure><p>Both sessions got a gap lock, on the same gap, at the same time. LOCK_DATA 30 with mode X,GAP means &quot;the gap before record 30&quot;, which is the open interval (20, 30) where both 25 and 27 would go. Nothing was found, so nothing else was locked.</p><p>Then A’s INSERT needed an insert intention lock on that gap, and B&#39;s gap lock blocked it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Kow0Mnz4HMv7E46czs-BGQ.png" /></figure><p>When B’s INSERT asked for the same thing, each session was waiting for a lock the other held. InnoDB detected the cycle immediately, rolled back B with ERROR 1213, and A&#39;s insert went through. A had waited 0.504 seconds, which is just how long my script paused before sending B&#39;s insert.</p><p>The deadlock report in SHOW ENGINE INNODB STATUS says the same thing in its own vocabulary. Each transaction <strong>holds</strong> lock_mode X locks gap before rec and is <strong>waiting for</strong> lock_mode X locks gap before rec insert intention waiting, on the same record. The record&#39;s first field is printed as hex 8000001e: that&#39;s 30, with InnoDB&#39;s sign bit set.</p><p>I then ran the same script three more ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*0agEAhZ_DymJMRpcEWXWgQ.png" /></figure><p>READ COMMITTED removes this deadlock because a locking read that finds nothing takes no gap lock there. It doesn&#39;t make the race go away, though. With the same key, it turns a deadlock into a duplicate-key error, so the application still has to handle a failed insert. It just gets a more honest error message.</p><h3>Experiment 2: how much a range UPDATE really locks</h3><p>Session A ran one statement and kept its transaction open:</p><pre>BEGIN;<br>UPDATE t SET v = v + 1 WHERE k BETWEEN 30 AND 50;   -- matches rows 30, 40, 50</pre><p>Then session B, with innodb_lock_wait_timeout=1, tried 16 single-row inserts spread across the index, and recorded which ones timed out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*roIYQwuVMRms2hKYPgj4gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*s7AXMW7Jzpryih03KQh7rA.png" /></figure><p>Lab run range_rr from dl_lab.py · MySQL 8.0.46, REPEATABLE READ · 16 single-row inserts from a second session, innodb_lock_wait_timeout=1</p><p>Three things stand out.</p><p><strong>The lock runs past the end of the range.</strong> To be sure no k=50 row is missing, the scan has to read the next entry, (60, 60), and under REPEATABLE READ it locks what it reads. So inserts with k = 55 were blocked even though 55 isn&#39;t between 30 and 50. So was a plain UPDATE ... WHERE id = 60 from session B: row 60 was locked by a statement that didn&#39;t match it. Updates to rows 20 and 70 went straight through.</p><p><strong>The boundaries are in (k, id) order, not k order.</strong> A secondary index entry is really the pair (k, primary key). That’s why inserting k = 20 was blocked with id = 1020 but allowed with id = 19: (20, 19) sorts before the entry (20, 20), outside the locked gap, while (20, 1020) sorts after it, inside. The same thing happened at the top: k = 60 was blocked with id = 59 and allowed with id = 1060. If you’ve seen an insert block seemingly at random depending on the id it got, this is one explanation worth checking.</p><p><strong>Under READ COMMITTED, none of this happened.</strong> The same UPDATE took record locks on the three matching rows only. All 16 inserts succeeded.</p><p>Then the case that turns this from surprising into dangerous. With no index on the filtered column:</p><pre>BEGIN;<br>UPDATE t SET v = v + 1 WHERE v = 999;   -- v isn&#39;t indexed; matches nothing</pre><p>Under REPEATABLE READ, that statement matched zero rows and still took next-key locks on all ten rows plus the supremum pseudo-record (the end of the index). Every one of B&#39;s 16 inserts was blocked, from k = 5 to k = 105. One UPDATE with a missing index blocked every insert into the table and held an exclusive lock on every row until it committed. Under READ COMMITTED, the same statement held only its table intention lock, and nothing was blocked: non-matching rows had their locks released after the WHERE clause was evaluated, as the <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html">isolation levels page</a> describes.</p><h3>Experiment 3: the duplicate-key deadlock, and why READ COMMITTED doesn’t save you</h3><p>The manual’s <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html">Locks Set by Different SQL Statements</a> page describes a deadlock that needs no gap locks at all. I ran it exactly as written:</p><pre>-- S1                       -- S2                        -- S3<br>BEGIN;                      BEGIN;                       BEGIN;<br>INSERT INTO t1 VALUES (1);<br>                            INSERT INTO t1 VALUES (1);   -- waits<br>                                                         INSERT INTO t1 VALUES (1);   -- waits<br>ROLLBACK;</pre><p>While S2 and S3 waited, data_locks showed both of them waiting for an S,REC_NOT_GAP lock on row 1. A duplicate-key check takes a <em>shared</em> lock on the existing row. When S1 rolled back, both shared locks were granted. Then S2 and S3 each needed an exclusive lock to actually insert, and each was blocked by the other&#39;s shared lock. S3 got ERROR 1213; S2&#39;s insert succeeded after 0.81 seconds.</p><p>The deadlock report shows an extra detail worth knowing. Once S1’s row was gone, the waiting locks were recorded against heap no 1, the supremum record, and each transaction was waiting for lock_mode X insert intention. The shared locks on a deleted row became locks on a gap.</p><p>Then I ran it again under READ COMMITTED: <strong>same deadlock</strong>, same victim, same final row. That matches the manual&#39;s <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-deadlocks.html">deadlock page</a>, which says the possibility of deadlocks isn&#39;t affected by the isolation level. Duplicate-key checking is one of the two places READ COMMITTED still uses gap locks, and as far as I can tell this deadlock comes from that path.</p><p>So the honest summary of READ COMMITTED is narrower than &quot;it prevents deadlocks&quot;. It removes the gap locks that searches and scans take, which removed the deadlocks in Experiments 1 and 2. Deadlocks from duplicate-key checks are still there, and so, by the same reasoning, are deadlocks from two transactions locking ordinary rows in opposite orders (a case I didn&#39;t run here).</p><h3>Experiment 4: upsert patterns under concurrency</h3><p>Scripted scenarios show that a deadlock <em>can</em> happen. To see how often it <em>does</em>, I ran 8 threads for 20 seconds, each repeatedly upserting a random key, in two patterns:</p><pre>-- check-then-insert (4 round trips)<br>BEGIN;<br>SELECT n FROM counters WHERE id = ? FOR UPDATE;<br>INSERT INTO counters VALUES (?, 1);          -- or UPDATE ... SET n = n + 1 if a row came back<br>COMMIT;</pre><pre>-- single-statement upsert (autocommit)<br>INSERT INTO counters VALUES (?, 1) ON DUPLICATE KEY UPDATE n = n + 1;</pre><p>I ran them on two workloads. Insert-heavy draws keys from 10 million, so almost every operation inserts a new row. Update-heavy draws from 2,000 keys, which fill up within the first few seconds, so after that almost every operation updates an existing row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*AhS3fANa-hQ-Pj1i_ccO3A.png" /></figure><p>The insert-heavy column comes from two 20-second runs per row, each about 40,000 attempts for check-then-insert and 75,000–84,000 for the upsert. No run had a lock wait timeout.</p><p>Five or eight deadlocks per 10,000 sounds small until you put it in production terms. At 1,000 inserts a second, that’s roughly one deadlock every one to two seconds, every one of them a failed request unless the application retries.</p><p>The single-statement upsert had none, on either workload, under either isolation level. I wouldn’t claim it can never deadlock: the manual notes that it takes exclusive locks on duplicates, and other access patterns, such as multi-row upserts or tables with extra unique keys, are outside what I tested. For this single-key shape, though, it was both safer and faster. Its throughput advantage is most likely round trips: one statement against four, on a 2-vCPU VM where every round trip costs CPU.</p><p>Check-then-insert under READ COMMITTED didn&#39;t deadlock either, but in the update-heavy run it produced 4 duplicate-key errors: two threads both found the key missing, and the second insert failed. That&#39;s the same race Experiment 1 showed, with a different error code.</p><h3>Reading a deadlock, and what to monitor</h3><h3>LATEST DETECTED DEADLOCK</h3><p>SHOW ENGINE INNODB STATUS shows the most recent deadlock only. Each report has the same four parts per transaction, and they read best in this order:</p><ol><li><strong>The statement</strong> under *** (n) TRANSACTION. That&#39;s the statement that was waiting, not necessarily the one that took the conflicting lock earlier in the transaction.</li><li><strong>HOLDS THE LOCK(S)</strong> and <strong>WAITING FOR THIS LOCK TO BE GRANTED</strong>. The lock description is the key: locks gap before rec is a gap lock, insert intention waiting is an insert blocked by someone&#39;s gap, locks rec but not gap is a plain record lock, and plain lock_mode X with neither phrase is a next-key lock.</li><li><strong>The record</strong>. Field 0 is the index key in InnoDB’s internal format: hex 8000001e is 30, with the sign bit set. heap no 1 is the supremum, meaning &quot;the end of the page&quot;, which is how a lock on &quot;everything after the last row&quot; appears.</li><li><strong>WE ROLL BACK TRANSACTION (n)</strong>: the victim.</li></ol><p>Because only the latest deadlock is kept, one report tells you what happened once, not what keeps happening. innodb_print_all_deadlocks (off by default) writes every report to the error log. In my test, one deadlock added 42 lines, so leave it on only while you&#39;re investigating, or make sure your log rotation can take it.</p><h3>data_locks: join on the transaction, not the thread</h3><p>While a lock wait is in progress, performance_schema.data_locks and data_lock_waits show it live. But Experiments 1 and 3 turned up a trap. During a duplicate-key check, the inserting transaction&#39;s implicit lock is made explicit by the session that&#39;s checking. In 8.0.46 that lock was recorded with the <em>checker&#39;s</em> THREAD_ID, while its ENGINE_TRANSACTION_ID still belonged to the inserter.</p><p>I tested three ways of finding the blocker while session B (pid 10) waited on a duplicate key held by session A (pid 9):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*NyHDTbiRYYsSThc7Vnz8cw.png" /></figure><p>If you write your own lock queries, join on the transaction:</p><pre>SELECT l.ENGINE_TRANSACTION_ID AS trx_id,<br>       trx.trx_mysql_thread_id AS owner_pid,<br>       l.OBJECT_NAME, l.INDEX_NAME, l.LOCK_MODE, l.LOCK_STATUS, l.LOCK_DATA<br>FROM performance_schema.data_locks l<br>LEFT JOIN information_schema.INNODB_TRX trx<br>       ON trx.trx_id = l.ENGINE_TRANSACTION_ID<br>WHERE l.LOCK_TYPE = &#39;RECORD&#39;<br>ORDER BY l.ENGINE_TRANSACTION_ID;</pre><p>And read LOCK_DATA together with LOCK_MODE. X,GAP on 30 means the gap <em>before</em> 30. X on 60, 60 in a secondary index means the entry (k=60, id=60) and the gap before it. supremum pseudo-record means the end of the index.</p><h3>What I’d put in place</h3><ol><li><strong>Count deadlocks.</strong> lock_deadlocks in information_schema.INNODB_METRICS is enabled by default and matched my client-side count exactly in every benchmark run. Graph its rate.</li><li><strong>Retry on 1213, everywhere.</strong> The manual is explicit that you must be prepared to retry. A retry loop of a few attempts, with a short random pause between them, turns a deadlock into a latency blip.</li><li><strong>Prefer single-statement upserts</strong> over check-then-insert for get-or-create logic. In Experiment 4 they had no deadlocks and twice the throughput.</li><li><strong>Index every column you filter on in </strong><strong>UPDATE, </strong><strong>DELETE and </strong><strong>SELECT ... FOR UPDATE.</strong> Experiment 2&#39;s unindexed UPDATE locked the whole table while matching nothing.</li><li><strong>Consider READ COMMITTED for write-heavy OLTP</strong>, if the application doesn’t rely on repeatable reads. It removed every gap-lock deadlock I produced. It didn’t remove the duplicate-key one, and with binary logging it requires row-based replication, so treat it as a design decision, not a quick fix.</li><li><strong>Treat 1062 and 1213 as the same family.</strong> Under READ COMMITTED, the check-then-insert race shows up as duplicate-key errors instead of deadlocks. The application has to handle one or the other.</li></ol><h3>What I didn’t prove</h3><ul><li><strong>Scale and shape.</strong> Ten rows for the scripted scenarios, one simple table for the benchmark, 8 threads on a 2-vCPU VM. Real schemas with several unique keys, foreign keys and multi-row statements have more ways to deadlock than I tested.</li><li><strong>That upserts never deadlock.</strong> INSERT ... ON DUPLICATE KEY UPDATE had zero deadlocks in my single-key workloads. Multi-row upserts and tables with more than one unique key are a known source of deadlocks that I didn&#39;t measure.</li><li><strong>Opposite-order row locking.</strong> The classic “A locks row 1 then row 2, B locks row 2 then row 1” deadlock isn’t covered here, because it doesn’t depend on gaps or isolation level.</li><li><strong>An observation I didn’t chase.</strong> In one test run I deleted rows 25 and 27 just before running the check-then-insert script on those same keys, and it didn’t deadlock. My guess is that the delete-marked rows, not yet purged (see part 4), changed which locks the SELECT ... FOR UPDATE took. I didn&#39;t investigate further, so treat that as a hypothesis.</li><li><strong>Versions.</strong> Everything ran on MySQL 8.0.46. Lock behaviour has changed across releases, and I didn’t test 8.4 or 9.x.</li></ul><h3>Try it yourself</h3><p>The lab is in the same companion repo as the earlier parts. dl_lab.py runs every scenario: check_insert (with --iso and --same-key), range_map (with --where), dup3, and bench (with --pattern, --iso, --threads, --secs and --keyspace). dl_show.py prints any result, and dl_checks.py reproduces the blocker-attribution comparison and the deadlock-logging test. The raw JSON for every run is in results/dl/.</p><p>Open question: the public GitHub URL for the scripts. Add it here before publishing.</p><p>Sources:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html">MySQL 8.0 Reference Manual: InnoDB Locking</a> record, gap, next-key and insert intention locks</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html">MySQL 8.0 Reference Manual: Locks Set by Different SQL Statements in InnoDB</a> — scanned-row locking, the three-session duplicate-key example, INSERT ... ON DUPLICATE KEY UPDATE</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html">MySQL 8.0 Reference Manual: Transaction Isolation Levels</a> READ COMMITTED lock behaviour</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-deadlocks.html">MySQL 8.0 Reference Manual: Deadlocks in InnoDB</a> detection, innodb_print_all_deadlocks, isolation level and deadlock possibility, retry advice</li></ul><p><em>Next in MySQL Under Pressure: redo log capacity and checkpoint stalls.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b401f34cfa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Idle SELECT Grew My History List to 178,000]]></title>
            <link>https://yasharainduwara.medium.com/one-idle-select-grew-my-history-list-to-178-000-aba700bd5be8?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba700bd5be8</guid>
            <category><![CDATA[innodb]]></category>
            <category><![CDATA[purge]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 14:00:01 GMT</pubDate>
            <atom:updated>2026-12-02T14:00:01.750Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MySQL Under Pressure, Part 4 - purge lag and the cost of an open snapshot</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NC0oHkJwqmFaWBR1TKb7Q.jpeg" /></figure><p>History list length is a number many of us glance at in SHOW ENGINE INNODB STATUS without being sure what a bad value looks like, or what it actually costs. The manual&#39;s answer is that it&#39;s usually under a few thousand on a healthy server. It doesn&#39;t say what happens to your workload when it isn&#39;t.</p><p>So I measured it. On MySQL 8.0.46 I ran a small but realistic write workload: two threads updating a hot table, and a job queue where one thread inserts work and another deletes it. Then I opened one transaction, ran a single SELECT, and left it idle for two minutes. I tracked the history list, undo tablespace size, query latency and throughput twice a second, and repeated the run with every kind of &quot;idle&quot; transaction I could think of.</p><p>As in <a href="https://yasharainduwara.medium.com/i-crashed-mysql-31-times-to-see-what-it-really-loses-378a40281221">part 1</a> through part 3, the scripts and raw output are linked at the end, and I say plainly where I’m reasoning beyond what I measured.</p><p><strong>The short version</strong></p><ul><li>One idle REPEATABLE READ transaction that had read a single row pushed the history list from about 700 to <strong>178,166 in two minutes</strong>.</li><li>The job queue’s “next job” query, SELECT id FROM queue ORDER BY id LIMIT 1, got <strong>about 14–15 times slower</strong>, even though the queue usually held only a few live rows. Primary-key reads and index range reads from other sessions didn&#39;t measurably change.</li><li>Update throughput was 41–55% lower than the control run in the second minute.</li><li>START TRANSACTION WITH CONSISTENT SNAPSHOT, with no statement after it, did the same damage. So did a Python app on PyMySQL&#39;s default settings that ran one SELECT and never called commit(). A READ COMMITTED transaction, a bare BEGIN and an autocommit SELECT did no damage at all.</li><li>Once the transaction committed, purge cleared the backlog in about 1.5 seconds. The undo files, which had grown from 32 MB to 128 MB, <strong>didn’t shrink</strong>, because with defaults they only truncate above 1 GiB.</li><li>SHOW ENGINE INNODB STATUS showed the symptom but didn&#39;t list the idle transaction as active. information_schema.INNODB_TRX found it immediately.</li></ul><h3>How purge works, briefly</h3><p>When InnoDB updates a row, it changes it in place but first writes the previous version to an undo log, and the rollback segment is what InnoDB uses to rebuild earlier versions of a row for a consistent read (<a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-multi-versioning.html">InnoDB Multi-Versioning</a>). Deletes work the same way: a deleted row isn’t physically removed right away; it stays until it’s no longer needed for multi-version concurrency control (<a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-purge-configuration.html">Purge Configuration</a>).</p><p>Cleaning all that up is purge’s job. The <strong>history list</strong> is the queue it works from: a list of undo log pages for committed transactions. Purge removes delete-marked rows and frees undo log pages from the history list once nothing needs them any more.</p><p>The catch is in “once nothing needs them”. Undo for an insert can go the moment the transaction commits. Undo for an update can only be discarded once no transaction holds a snapshot that could still need it. That’s why the manual tells you to commit regularly, including transactions that only do consistent reads. Otherwise InnoDB can’t discard update undo, and the undo tablespace fills up.</p><p>The purge page puts it even more directly. A write-heavy workload or long-running transactions can make the history list grow, even when those transactions are read only. Its two examples are mysqldump --single-transaction running during heavy DML, and a SELECT with autocommit disabled and no COMMIT or ROLLBACK. It says a healthy history list is usually less than a few thousand.</p><p>So the mechanism is documented. What it doesn’t tell you is how fast the list grows, what gets slower as it does, which kinds of “idle” transaction actually trigger it, and whether you get your disk space back afterwards.</p><h3>How I tested it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*N27-QrEfk7dsZCkWBhxmRQ.png" /></figure><p>The history list length comes from information_schema.INNODB_METRICS (trx_rseg_history_len), which was enabled by default on this install. It&#39;s the same counter as the History list length line in SHOW ENGINE INNODB STATUS, and easier to graph.</p><p>I ran the two-minute blocked run twice, plus a control with no blocker on the same timeline. Where the two blocked runs differ, I give both numbers.</p><h3>Experiment 1: the growth</h3><p>The blocker was as innocent as it gets:</p><pre>BEGIN;<br>SELECT * FROM lab.hot WHERE id = 1;<br>-- nothing else for two minutes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*DBZaICQmNw4JPd7rvexXfQ.png" /></figure><p>Without the blocker, the history list hovered between a few hundred and about 1,300 for the whole run, which is purge keeping up. With it, the list grew by roughly 1,500 entries a second, a straight line for as long as the snapshot stayed open: 712 when the transaction started, about 103,000 after one minute, <strong>178,166</strong> after two. The second blocked run reached 149,666. Its updaters also ran slower, so there was less history to pile up.</p><p>The undo tablespaces grew along with it. The two undo files started at 16 MB each (32 MB total) and ended at 128 MB total in the first run and 96 MB in the second. In the control run they never moved from 32 MB.</p><p>Nothing about this needs a big or busy server. Two update threads on a thousand-row table were enough to push the history list far past the manual’s “a few thousand” in under five seconds, and to keep it climbing.</p><h3>Experiment 2: who actually gets slower</h3><p>“A long transaction slows the whole server down” is the usual summary. The measurements say something more specific: three things got slower, and most queries didn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*fvYtQMGiNrmB9a1I2h-ahQ.png" /></figure><p>Where a cell shows two numbers, they’re the two blocked runs.</p><p><strong>The job queue took the hit.</strong> Its “next job” query went from about 0.15 ms to over 2 ms, roughly 14–15 times slower, with single samples up to 3.9 ms. The queue itself usually held only a few live rows (peaking at 72 and 152 in the two runs, when the consumer briefly fell behind). What it did hold was every row the consumer had deleted since the snapshot opened: about 28,000 and 25,000 of them. A delete only marks the row; purge removes it later. Until then, ORDER BY id LIMIT 1 has to step over all the delete-marked rows at the front of the index to find the first live one. That explanation follows from the documented purge behaviour; the measured part is the slowdown and the fact that it vanished once purge ran (back to about 0.2 ms).</p><p>Any table used as a queue, an outbox or a sliding window, where rows are inserted at one end and deleted from the other, has this shape. Those are often exactly the tables a system’s latency depends on.</p><p><strong>The blocker itself slowed down badly.</strong> Its full read of the 1,000-row table went from under half a millisecond to 86–227 ms, because every row it reads has been updated many times since its snapshot, and InnoDB has to walk back through undo to rebuild the version it’s allowed to see. This matters more than it sounds: the long-running reporting query or mysqldump --single-transaction that&#39;s holding the snapshot gets slower the longer it runs, which makes it run even longer.</p><p><strong>Writes slowed down too, and I can’t fully explain why.</strong> In the second minute, updates ran 41–55% below the control. In one run throughput recovered after the commit; in the other it stayed low, so I can’t say for certain that the history list is the whole cause. On a 2-vCPU VM, purge threads and the probe compete for the same CPUs, which may play a part.</p><p><strong>Ordinary reads from other sessions didn’t measurably change.</strong> Primary-key and index range reads on the hot table rose by a few hundredths of a millisecond, about the same drift as the control run. A new autocommit statement reads the latest committed version of each row, so it never has to walk the long undo chains the blocker is holding open.</p><h3>Experiment 3: which “idle” transactions actually block purge</h3><p>Not every open transaction holds purge back, and the difference is easy to get wrong in both directions. I ran six kinds of blocker, each idle for the same 60 seconds against the same workload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*B1F7bHiLGLgxVdv8nccP1w.png" /></figure><p><em>The REPEATABLE READ row comes from the two-minute runs: the history list at the one-minute mark, and the undo size at the end of each run.</em></p><p>The pattern follows from how REPEATABLE READ works. The snapshot (InnoDB calls it a read view) is created at the transaction&#39;s first consistent read and kept until the transaction ends. START TRANSACTION WITH CONSISTENT SNAPSHOT creates it immediately, which is why it did the same damage without running a single query. mysqldump --single-transaction works the same way: it opens a REPEATABLE READ transaction before it starts dumping, and the manual&#39;s purge page names it as an example of what makes the history list grow.</p><p>READ COMMITTED creates a fresh read view for each statement and drops it when the statement ends, so an RC transaction sitting idle between statements doesn&#39;t pin anything. That doesn&#39;t make RC transactions free: one long-running <em>statement</em> holds its read view for as long as it runs. I didn&#39;t test that case here.</p><p>A bare BEGIN doesn&#39;t create a read view at all, so it did no harm. That cuts both ways: &quot;the transaction has been open for an hour&quot; isn&#39;t enough to blame it, and &quot;it only ran a SELECT&quot; isn&#39;t enough to clear it.</p><p>The PyMySQL row is the one I’d point application teams to. In part 2, I found that PyMySQL’s defaults run with autocommit=0. Here, the server&#39;s statement history for that connection showed exactly what the library sent on its own: SET NAMES utf8mb4, SET AUTOCOMMIT = 0, then my one SELECT. No BEGIN in sight, yet a REPEATABLE READ snapshot that held purge back for as long as the connection sat idle. A read-only request handler that never calls commit() and returns its connection to a pool can do this indefinitely.</p><h3>Experiment 4: after the commit</h3><p>The good news first: purge caught up almost instantly. In both two-minute runs, the history list went from 150,000–178,000 to under 1,000 within about 1.5 seconds of the COMMIT, and the queue’s “next job” query was back to about 0.2 ms.</p><p>That speed reflects a small, fully cached data set on four purge threads. On a server where the undo and the delete-marked pages have been pushed out of the buffer pool, I’d expect catch-up to take much longer, but I didn’t test that.</p><p>The disk space is a different story. With default settings, the undo files that had grown to 128 MB (first run) and 96 MB (second run) were still that size 80 seconds after purge had finished. Nothing was wrong: automatic truncation is on by default, but it only acts on an undo tablespace larger than innodb_max_undo_log_size, which defaults to 1 GiB (<a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-undo-tablespaces.html">Undo Tablespaces</a>). Below that, the space stays allocated inside the files.</p><p>To confirm truncation really gives the space back, I repeated a 60-second blocked run with innodb_max_undo_log_size set to its 10 MiB minimum. The undo files grew to 80 MB while the snapshot was open, then shrank back to 32 MB (16 MB each, the documented initial size) within about seven seconds of the commit.</p><p>So after an incident like this, expect two things. Performance comes back as soon as purge finishes. Disk space only comes back if a file crossed the truncation threshold, or if you truncate it manually, which the manual describes and which has prerequisites worth reading before you need it. Planning undo disk around the 1 GiB default threshold, rather than the 16 MB starting size, is the safer assumption.</p><h3>Finding the culprit, and what to do</h3><h3>What SHOW ENGINE INNODB STATUS shows, and doesn&#39;t</h3><p>I captured the status output 15 seconds into a blocked run, with the PyMySQL session as the blocker. The symptom is plain in the header of the TRANSACTIONS section:</p><pre>Trx id counter 29112<br>Purge done for trx&#39;s n:o &lt; 1318 undo n:o &lt; 0 state: running but idle<br>History list length 13821</pre><p>Purge is stuck at transaction 1318 while new transactions are numbered past 29,000, and it says “running but idle”: purge isn’t slow, it has nothing it’s allowed to do.</p><p>What the section didn’t show me was the culprit. The only entry marked ACTIVE was one of the updater&#39;s transactions mid-commit. The idle read-only transaction holding the snapshot didn&#39;t appear as active anywhere in the list. So the status output tells you that something is holding purge back, not who.</p><h3>The query that found it</h3><p>information_schema.INNODB_TRX lists every open transaction, read-only ones included. Ordered by start time and joined to the processlist, the blocker was the first row:</p><pre>SELECT t.trx_mysql_thread_id                       AS pid,<br>       p.USER, p.HOST, p.COMMAND,<br>       p.TIME                                      AS state_seconds,<br>       TIMESTAMPDIFF(SECOND, t.trx_started, NOW()) AS trx_age_s,<br>       t.trx_isolation_level,<br>       t.trx_rows_modified,<br>       p.INFO                                      AS running_now<br>FROM information_schema.INNODB_TRX t<br>JOIN information_schema.PROCESSLIST p ON p.ID = t.trx_mysql_thread_id<br>ORDER BY t.trx_started<br>LIMIT 5;</pre><pre>pid=10  USER=app  COMMAND=Sleep  state_seconds=15  trx_age_s=15<br>trx_isolation_level=REPEATABLE READ  trx_rows_modified=0  running_now=NULL</pre><p>That row is the signature to look for: an old transaction, in Sleep, running nothing, having modified nothing, at REPEATABLE READ. Its statement history in performance_schema.events_statements_history then tells you which code opened it (here: SET AUTOCOMMIT = 0, then a SELECT), which is the part you actually need to fix. Experiment 3 is the reason to check the isolation level before you act: an old READ COMMITTED transaction sitting idle wasn&#39;t holding anything back in my tests.</p><h3>What I’d put in place</h3><ol><li><strong>Alert on the history list, not just disk.</strong> trx_rseg_history_len from INNODB_METRICS is cheap to scrape. In my lab it passed 5,000 within three seconds of the snapshot opening, so a threshold in the tens of thousands, sustained for a minute or two, catches this long before the undo files grow.</li><li><strong>Alert on old transactions directly.</strong> The query above with a trx_age_s threshold finds the cause rather than the symptom.</li><li><strong>Fix the clients.</strong> Use autocommit for reads, or commit at the end of every request, including read-only ones. Check your driver’s default; PyMySQL’s isn’t autocommit.</li><li><strong>Schedule </strong><strong>mysqldump --single-transaction and long reports with this in mind.</strong> They hold a snapshot for their whole run, and Experiment 2 showed the snapshot holder itself gets slower as history piles up.</li><li><strong>Watch your queue-shaped tables.</strong> They’re the first ordinary workload to feel it.</li><li><strong>Decide what to do about undo disk.</strong> Either accept that the files keep their high-water mark below 1 GiB, or lower innodb_max_undo_log_size after testing what truncation costs on your system.</li></ol><p>There is one built-in brake I deliberately didn’t recommend: innodb_max_purge_lag. It&#39;s off by default (0); when set, it delays INSERT, UPDATE and DELETE once the purge lag passes the threshold. When purge is blocked by an open snapshot rather than overwhelmed, slowing writes doesn&#39;t remove the blocker. I haven&#39;t measured it, so I&#39;ll leave that as reasoning.</p><h3>What I didn’t prove</h3><ul><li><strong>Scale.</strong> One small, fully cached data set on a 2-vCPU VM. At production size, purge catch-up after a long snapshot can take far longer than 1.5 seconds, and more queries may have to walk old versions from disk. I expect the shape to hold; I haven’t measured the magnitudes.</li><li><strong>The write slowdown’s cause.</strong> Updates ran 41–55% slower during the second minute in both blocked runs, but one run didn’t recover after the commit, so I can’t say the history list is the whole explanation.</li><li><strong>Long statements under READ COMMITTED.</strong> RC’s per-statement read view means one long-running statement should hold purge back for as long as it runs. I didn’t test it.</li><li><strong>innodb_max_purge_lag.</strong> I describe what the manual says it does and argue it doesn&#39;t address a blocked purge, but I didn&#39;t run it.</li><li><strong>Versions.</strong> Everything ran on MySQL 8.0.46. I didn’t test 8.4 or 9.x.</li></ul><h3>Try it yourself</h3><p>The lab is in the same companion repo as the earlier parts. hll_lab.py runs the workload and the blocker (--blocker rr | rc | begin_only | autocommit | snapshot | pymysql_default | none, with --block-at, --block-until, --tail and --max-undo), hll_summary.py prints any run as a timeline, and hll_checks.py reproduces the diagnostics section. The raw JSON for every run is in results/hll/.</p><p>Open question: the public GitHub URL for the scripts. Add it here before publishing.</p><p>Sources:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-purge-configuration.html">MySQL 8.0 Reference Manual: Purge Configuration</a> - the history list, purge threads, innodb_max_purge_lag, long-running and read-only transactions</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-multi-versioning.html">MySQL 8.0 Reference Manual: InnoDB Multi-Versioning</a> - undo logs, when update undo can be discarded, committing consistent-read transactions regularly</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-undo-tablespaces.html">MySQL 8.0 Reference Manual: Undo Tablespaces</a> -innodb_max_undo_log_size, truncation, the 16 MiB initial size</li></ul><p><em>Next in MySQL Under Pressure: reading deadlocks properly, gap locks, next-key locks and what </em><em>performance_schema.data_locks actually tells you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba700bd5be8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seconds_Behind_Source Said Zero. My Replica Disagreed.]]></title>
            <link>https://yasharainduwara.medium.com/seconds-behind-source-said-zero-my-replica-disagreed-e8d35bab8068?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8d35bab8068</guid>
            <category><![CDATA[mysql-error]]></category>
            <category><![CDATA[database-replication]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[fractuies]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 02:36:01 GMT</pubDate>
            <atom:updated>2026-11-25T02:36:01.556Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MySQL Under Pressure, Part 3 - replication lag forensics</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hf97MnkZjJ9hUNmCJ9MzJQ.jpeg" /></figure><p>Many replication dashboards are built around one number: Seconds_Behind_Source (Seconds_Behind_Master before 8.0.22). Read replicas get pulled out of rotation by it, alerts fire on it, and on-call engineers go back to sleep when it reads 0.</p><p>I wanted to know exactly when that number can be trusted. So I set up a source and a replica on MySQL 8.0.46, put a small TCP proxy between them that I could slow down or silently cut, and wrote a heartbeat row on the source every 100 ms as ground truth. Then I compared what Seconds_Behind_Source said with how stale the replica actually was, twice a second, through a slow network, a dead network and a big transaction.</p><p>As in <a href="https://yasharainduwara.medium.com/i-crashed-mysql-31-times-to-see-what-it-really-loses-378a40281221">part 1</a> and part 2, the scripts and raw output are linked at the end. Where I’m going beyond what I measured, I say so.</p><p><strong>The short version</strong></p><ul><li>When the network silently stopped delivering data, the replica reported Replica_IO_Running: Yes, Waiting for source to send event and Seconds_Behind_Source: 0 <strong>for 60 seconds</strong>, while it fell 59.8 seconds behind. Then the value went to NULL, not to a number.</li><li>On a slow link with light traffic, Seconds_Behind_Source read 0 in 91% of samples while the replica was up to 15.4 seconds behind.</li><li>On the same slow link with steady traffic, it was accurate to within 0.83 seconds. The failure depends on your traffic pattern, which is why it’s so easy to miss in testing.</li><li>During a 1-million-row UPDATE, it read 3.6 to 4.2 seconds higher than the true lag, which matches the 4.2 seconds the source spent running the statement.</li><li>Two performance_schema timestamps, paired with a heartbeat, tracked the true lag in every scenario and told me whether the delay was in the network or in the applier.</li></ul><h3>What the number actually measures</h3><p>The <a href="https://dev.mysql.com/doc/refman/8.0/en/show-replica-status.html">SHOW REPLICA STATUS reference</a> is more honest about this field than most dashboards are. Three passages matter.</p><p><strong>It compares two threads on the replica, not the replica with the source.</strong> While the replica is processing updates, the value is the replica’s current time minus the original timestamp logged on the source for the event currently being processed. In the manual’s words, it measures the time difference between the applier (SQL) thread and the receiver (I/O) thread. Anything the receiver hasn’t fetched yet doesn’t count.</p><p><strong>It reads 0 whenever the applier has nothing to do.</strong> When no event is being processed, the value is 0. If the receiver is running but the relay log is exhausted, it’s also set to 0. It’s NULL only when the applier isn&#39;t running, or when the applier has drained the relay log and the receiver isn&#39;t running.</p><p><strong>The manual says outright that it’s only useful on fast networks.</strong> On a slow network, the applier is often caught up with a slow receiver, so the value often shows 0 even when the receiver is late compared to the source.</p><p>Two smaller caveats from the same page: the calculation assumes the clock difference between source and replica, measured when the receiver thread starts, stays constant (NTP adjustments can break that), and on a multithreaded replica the value is based on Exec_Source_Log_Pos, so it may not reflect the most recently committed transaction.</p><p>None of this is hidden. But “only useful on fast networks” doesn’t tell you how wrong it gets, under which traffic patterns, or what to use instead. That’s what I set out to measure.</p><h3>How I tested it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*wy3VAORHouxF96cd4XPr6g.png" /></figure><p>Source and replica share a host, so they share a clock. That keeps the heartbeat honest, and it also takes clock skew out of the picture. On real hosts, both the heartbeat and Seconds_Behind_Source depend on clocks you need to keep in sync.</p><h3>Experiment 1: a slow network</h3><p>This is the case the manual warns about, so I expected Seconds_Behind_Source to read 0 and be wrong. It turned out more interesting than that: whether it lied depended entirely on how much traffic there was.</p><p>I ran the same 30-second throttle twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*58vMtAyiHx0ov6lpLZzF1g.png" /></figure><p>With steady traffic, Seconds_Behind_Source tracked the heartbeat almost exactly, climbing about 0.7 seconds every second for the whole throttle. With light traffic, it read 0 for most of the throttle while the replica fell steadily behind. The few non-zero readings, between 1 and 14, were the moments my sampler happened to catch the applier mid-event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mLFJKE076hAa4uJbYTCfZQ.png" /></figure><p>The manual’s definition explains the difference. With steady traffic, the applier is always in the middle of some event whose source timestamp is old, so the subtraction comes out right. With light traffic, each event trickles in, gets applied in a millisecond, and the applier goes idle again. Most of the time no event is being processed, so the value is 0, even though everything the replica has applied is 15 seconds old.</p><p>One reading on the chart needs a footnote. At 36.2 s, just after the throttle lifted, Seconds_Behind_Source read 17 while the heartbeat said the replica had caught up. My sampler reads the two a few milliseconds apart, and that was the instant the backlog flushed through, so I treat that point as a sampling artefact rather than a finding.</p><p>The catch for anyone who tests this: a load test with steady writes will tell you Seconds_Behind_Source is accurate. It&#39;s the quiet, low-traffic period, like a weekend batch window or an overnight link saturated by a backup transfer, where it can&#39;t see the lag.</p><h3>Experiment 2: a silent network drop</h3><p>This is the scenario I’d worry about most in production: the network path between source and replica stops delivering packets, but nothing sends a reset. A firewall state table expiring, a misbehaving load balancer, a half-dead switch. My proxy simulated it by holding every byte and keeping both sockets open. The source kept writing throughout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*p5ioEJu_aOkrw8nCgdl9uQ.png" /></figure><p>For 60 seconds after the drop, the replica’s status looked perfectly healthy:</p><pre>Replica_IO_Running: Yes<br>Replica_SQL_Running: Yes<br>Replica_IO_State: Waiting for source to send event<br>Seconds_Behind_Source: 0</pre><p>That held for all 120 samples between 5.0 s and 64.8 s, while the true lag climbed to 59.8 seconds. From the replica’s point of view, nothing was wrong: its receiver was connected and waiting, and its applier had nothing to apply. Waiting for the source to send an event is exactly what a healthy, idle replica does.</p><p>The replica only noticed at 65.3 s. replica_net_timeout is 60 seconds by default, and the receiver waited that long without hearing anything (heartbeats included, since the proxy swallowed those too) before it gave up and started reconnecting. At that point Replica_IO_Running went to Connecting and Seconds_Behind_Source went to NULL.</p><p>Two things are worth checking in your own alerting:</p><ul><li><strong>Does a 0 that should have been 60 trigger anything?</strong> In this run, nothing in SHOW REPLICA STATUS changed for a full minute.</li><li><strong>What does your alert do with </strong><strong>NULL?</strong> A check that compares the value against a threshold gets nothing from NULL, because NULL &gt; 30 isn&#39;t true. If your check treats NULL as &quot;no lag&quot; and never looks at Replica_IO_Running, this replica showed no lag for the entire outage: about 95 seconds from the drop until it reconnected.</li></ul><p>When the network came back at 95 s, the receiver reconnected within about 5 seconds (I set SOURCE_CONNECT_RETRY=5; the default is 60, which would have stretched the outage further). From then on, Seconds_Behind_Source agreed with the heartbeat to within a second all the way through catch-up: 95 s behind when it reconnected, still 27 s behind when the run ended 19 seconds later.</p><h3>Experiment 3: a big transaction</h3><p>The network was fine for this one. On the source I ran UPDATE lab.big SET v = v + 1 over 1,000,000 rows, which took 4.19 seconds to commit. The heartbeat and background writes carried on alongside it.</p><p>The replica then had to apply the same million row changes. While it did, nothing after the UPDATE could commit: with replica_preserve_commit_order=ON (the default since 8.0.27), later transactions wait for it, including the heartbeat. The true lag climbed by about a second per second, to 7.4 s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*fFtcxTe3ICdjUdT4MdHXiA.png" /></figure><p>Across all 14 samples during the apply, Seconds_Behind_Source read 3.6 to 4.2 seconds higher than the heartbeat. That band matches the 4.19 seconds the source spent executing the UPDATE, blurred by the fact that Seconds_Behind_Source is a whole number of seconds. The replica wasn&#39;t 11 seconds behind at the worst point; it was 7.4.</p><p>My reading of why, from the manual’s definition: the value is the replica’s clock minus the source timestamp of the event being processed. For a single big statement, that timestamp is from when the statement <em>started</em> on the source, not when it committed, so the source’s own execution time gets counted as lag. I’m inferring the timestamp detail from the numbers; I didn’t decode the binlog events to confirm it.</p><p>Overstating is the safer direction to be wrong. But if you set an alert threshold, or a load balancer’s “take the replica out of rotation” threshold, against this number, a large batch statement can trip it even when the replica is only a few seconds behind.</p><h3>Experiment 4: measuring lag properly</h3><p>The heartbeat was right in every scenario, so the first fix is simply to have one. A table on the source that gets NOW(6) written into it every second or less, and NOW(6) - ts read on the replica, is the old pt-heartbeat idea. It measures what you actually care about: how old the data on this replica is.</p><p>The heartbeat tells you <em>how far</em> behind you are, but not <em>why</em>. For that, MySQL 8.0 records each transaction’s original_commit_timestamp, when it committed on the original source, and exposes it in performance_schema (<a href="https://dev.mysql.com/doc/refman/8.0/en/replication-delayed.html">Delayed Replication</a>). Two columns split the lag in two:</p><ul><li><strong>Received age</strong>: now minus the source commit time of the newest transaction the receiver has queued (replication_connection_status.LAST_QUEUED_TRANSACTION_ORIGINAL_COMMIT_TIMESTAMP). If this is large, data isn&#39;t arriving. Look at the network or the receiver.</li><li><strong>Applied age</strong>: now minus the source commit time of the newest transaction any worker has applied (MAX(replication_applier_status_by_worker.LAST_APPLIED_TRANSACTION_ORIGINAL_COMMIT_TIMESTAMP)). This is the replica&#39;s real staleness. If it&#39;s large while the received age is small, the data is here and the applier can&#39;t keep up.</li></ul><p>Here is how they did against the heartbeat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*lQ1J5oRgEMGBzbCWTgd9HA.png" /></figure><p>Applied age matched the heartbeat to within 0.1 seconds in all four scenarios, including the two where Seconds_Behind_Source read 0. Received age correctly separated the network problems from the applier problem. During the catch-up after the silent drop, it also showed the hand-off: received age fell to near zero as soon as the network came back, while applied age was still draining when the run ended 19 seconds later. That&#39;s the signature of &quot;the network recovered and the applier is working through the backlog&quot;.</p><p>The query I used, tested on 8.0.46:</p><pre>SELECT<br>  c.SERVICE_STATE AS receiver,<br>  TIMESTAMPDIFF(MICROSECOND,<br>    c.LAST_QUEUED_TRANSACTION_ORIGINAL_COMMIT_TIMESTAMP, NOW(6)) / 1e6 AS received_age_s,<br>  (SELECT TIMESTAMPDIFF(MICROSECOND,<br>      MAX(w.LAST_APPLIED_TRANSACTION_ORIGINAL_COMMIT_TIMESTAMP), NOW(6)) / 1e6<br>   FROM performance_schema.replication_applier_status_by_worker w) AS applied_age_s<br>FROM performance_schema.replication_connection_status c;</pre><p>There’s one catch, and it’s why the heartbeat still matters. Both ages measure the time since the newest transaction <em>the source committed</em>. If the source is idle, they grow forever even on a perfectly healthy replica, because there’s nothing new to receive. In my lab the heartbeat wrote every 100 ms, so the source was never idle. Without a heartbeat, you can’t tell “the source is quiet” from “the replica is cut off”. With one, these two columns become reliable.</p><h3>What I’d monitor now</h3><p>Based on these four runs, here’s the setup I’d put in front of any replica that serves reads or stands by for failover.</p><ol><li><strong>A heartbeat is the lag metric.</strong> Write NOW(6) into a one-row table on the source every second (or less), and alert on NOW(6) - ts on each replica. It&#39;s the only measure here that was right in every scenario. Keep NTP healthy on both sides, because the subtraction crosses two clocks in production.</li><li><strong>Alert on thread state, not just on lag.</strong> Replica_IO_Running or Replica_SQL_Running not being Yes is an incident in itself. And treat a lag of NULL as &quot;unknown, page someone&quot;, never as &quot;no lag&quot;.</li><li><strong>Use received age and applied age to localise the problem.</strong> Large received age points to the network or the receiver. Small received age with large applied age points to the applier: a big transaction, a slow query on the replica, or not enough parallelism.</li><li><strong>Know your silent-failure window.</strong> With defaults, a replica that stops receiving data without a TCP reset looked healthy for 60 seconds (replica_net_timeout) in my test, and then retries every SOURCE_CONNECT_RETRY seconds (default 60). A heartbeat alert catches it long before either. If you lower replica_net_timeout, the heartbeat period it implies drops with it, so test the change rather than assuming.</li><li><strong>Keep </strong><strong>Seconds_Behind_Source as a secondary signal.</strong> It was accurate on a fast or busy link, and it&#39;s free. Just don&#39;t let it be the only thing between a stale replica and your users.</li></ol><h3>When the lag alert fires</h3><ul><li>Check the thread states first. A stopped thread with an error is a different incident from lag.</li><li>Run the received-age / applied-age query. That tells you whether to call the network team or look at the applier.</li><li>If it’s the applier, look at performance_schema.replication_applier_status_by_worker for what each worker is applying (APPLYING_TRANSACTION) and since when (APPLYING_TRANSACTION_START_APPLY_TIMESTAMP). One huge transaction looks very different from steady overload.</li><li>If it’s the network, compare RECEIVED_TRANSACTION_SET with the source&#39;s gtid_executed to see how much hasn&#39;t arrived.</li></ul><h3>What I didn’t prove</h3><ul><li><strong>The long-open-transaction spike.</strong> A common claim is that a transaction left open on the source makes Seconds_Behind_Source spike when it finally arrives. I tried: a transaction open for 15 seconds, sampled every 20 ms on the replica. I saw no spike, with a maximum reading of 1 across 1,142 samples. That doesn&#39;t disprove it: the replica applies such a transaction in milliseconds, so a spike could easily fall between samples. I&#39;m leaving it out rather than guessing.</li><li><strong>Clock skew.</strong> Source and replica shared one clock. On real hosts, a drifting clock affects both Seconds_Behind_Source and a heartbeat.</li><li><strong>Real networks.</strong> My proxy simulated throttling and silent drops at the application layer. Real packet loss, retransmits and TCP keepalives behave differently in the details, though the replica-side behaviour I measured depends only on bytes not arriving.</li><li><strong>The applier-side SBS mechanism.</strong> My explanation of why the big UPDATE was overstated comes from the manual’s definition and the numbers lining up, not from decoding the binlog events.</li><li><strong>Versions and topologies.</strong> Everything ran on 8.0.46 with one source and one replica. I didn’t test 8.4 or 9.x, multi-source replication, or Group Replication, which the manual says this metric doesn’t suit anyway.</li></ul><h3>Try it yourself</h3><p>The lab is in the same companion repo as parts 1 and 2. repl_lab.py sets up the source, the replica and the proxy, and runs each scenario (--scenario throttle | blackhole | big_update | sleepy_trx, with --load-rps, --rate and --sample-ms to change traffic, throttle and sampling). repl_summary.py prints any run as a timeline. The raw JSON for every run is in results/repl/.</p><p>Open question: the public GitHub URL for the scripts. Add it here before publishing.</p><p>Sources:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/show-replica-status.html">MySQL 8.0 Reference Manual: SHOW REPLICA STATUS</a> — how Seconds_Behind_Source is computed, when it&#39;s 0 or NULL, the slow-network caveat</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/replication-delayed.html">MySQL 8.0 Reference Manual: Delayed Replication</a> — original_commit_timestamp, immediate_commit_timestamp, Performance Schema as the recommended way to monitor delay</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/replication-administration-status.html">MySQL 8.0 Reference Manual: Checking Replication Status</a> — SHOW REPLICA STATUS replacing SHOW SLAVE STATUS from 8.0.22</li><li><a href="https://hackmysql.com/replica-preserve-commit-order/">Efficient MySQL Performance: Replica Preserve Commit Order and Measuring Lag</a> — the 8.0.27 default change for replica_preserve_commit_order</li></ul><p><em>Next in MySQL Under Pressure: history list length and purge lag, or how one forgotten transaction makes the whole server slower.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8d35bab8068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Idle Transaction Froze My Table: Metadata Lock Pile-ups, Measured]]></title>
            <link>https://yasharainduwara.medium.com/one-idle-transaction-froze-my-table-metadata-lock-pile-ups-measured-9fefc1df0fe8?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fefc1df0fe8</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-locks]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[alter-table]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 08:47:02 GMT</pubDate>
            <atom:updated>2026-11-24T08:47:02.561Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MySQL Under Pressure, Part 2</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3m6iQNN0p9FlCLn6KV4dEA.jpeg" /></figure><p>Every DBA eventually gets this call. Someone ran a quick ALTER TABLE, &quot;it&#39;s an instant operation, it can&#39;t hurt&quot;, and now the application is timing out, the connection count is at its limit, and nobody can find a slow query, because there isn&#39;t one.</p><p>The usual culprit isn’t the ALTER. It’s a transaction somebody opened minutes earlier and never closed.</p><p>I wanted numbers rather than folklore, so I rebuilt the incident in a lab on MySQL 8.0.46: 16 application threads reading one table, one connection that opens a transaction and goes idle, and one ALTER. Then I measured what happened to the readers, the connection count and the diagnostic views, under every DDL variant I could think of. As in <a href="https://yasharainduwara.medium.com/i-crashed-mysql-31-times-to-see-what-it-really-loses-378a40281221">part 1</a>, the scripts and raw output are linked at the end, and I say plainly where I’m reasoning beyond what I tested.</p><p><strong>The short version</strong></p><ul><li>One idle transaction plus one ALTER TABLE took reads on the table from about 2,900 queries per second to <strong>zero, for the full 10 seconds</strong> the transaction stayed open. The idle transaction had run a single-row SELECT.</li><li>ALGORITHM=INSTANT didn&#39;t help, and neither did ALGORITHM=INPLACE, LOCK=NONE or a READ COMMITTED blocker. Every variant froze reads for the same 10 seconds.</li><li>An application that opens a connection per request hit ERROR 1040: Too many connections less than 3 seconds into the freeze. Nothing in that error points at the real cause.</li><li>The blocker was invisible in SHOW PROCESSLIST: Sleep, no query text. sys.schema_table_lock_waits found it, but it also named the ALTER as a blocker, and offered a KILL for each.</li><li>SET SESSION lock_wait_timeout = 3 on the ALTER capped the freeze at 3 seconds. The default is one year.</li></ul><h3>How metadata locks work, in three rules</h3><p>InnoDB row locks get most of the attention, but this incident lives one layer up, in the server’s metadata locks (MDL). They protect a table’s <em>definition</em>, not its rows. Three rules from the manual explain everything that follows.</p><p><strong>Rule 1: a transaction holds its metadata locks until it ends.</strong> Every statement that touches a table takes a metadata lock on it, and inside a transaction the server defers releasing those locks until the transaction ends (<a href="https://dev.mysql.com/doc/refman/8.0/en/metadata-locking.html">Metadata Locking</a>). In autocommit mode, each statement is its own transaction, so the lock lasts only as long as the statement. That difference turns out to be the whole story.</p><p><strong>Rule 2: DDL needs an exclusive lock, and waits for it.</strong> A table an open transaction is using can’t be changed by DDL from another session until that transaction ends. Even online DDL needs the exclusive lock: in the commit phase it upgrades to exclusive to evict the old table definition, and it may take it briefly during preparation too (<a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-online-ddl-performance.html">Online DDL Performance and Concurrency</a>).</p><p><strong>Rule 3: a waiting write request goes ahead of new reads.</strong> The manual is blunt about it: write lock requests have higher priority than read lock requests. So while the ALTER waits for its exclusive lock, every new SELECT on that table queues <em>behind</em> the ALTER, even though plain reads don&#39;t conflict with the idle transaction at all. The online DDL page describes exactly this, with a three-session example where a SELECT is blocked by the exclusive lock the ALTER TABLE has requested.</p><p>Put the three together and you get the pile-up: the idle transaction blocks the ALTER (rule 2), and the waiting ALTER blocks everyone else (rule 3), for as long as the idle transaction lives (rule 1). The manual describes the mechanism. What it doesn’t tell you is how fast it turns into an outage, what your tools show while it happens, or which escape hatches actually work. That’s what I measured.</p><h3>How I tested it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*u1FJLXx1zGacGJMK36S0PA.png" /></figure><p>The blocker stays open for 10 seconds after the ALTER starts, then commits. A sampler polls the processlist and Threads_connected every 0.25 s, and every reader query&#39;s start and end times are recorded. Halfway through each freeze, the script captures what an on-call engineer would look at: SHOW PROCESSLIST, information_schema.INNODB_TRX, performance_schema.metadata_locks and sys.schema_table_lock_waits.</p><p>The application connects as an ordinary user, app, with no admin privileges. That detail matters for the connection storm in Experiment 1.</p><h3>Experiment 1: the freeze</h3><p>First, the control. With no open transaction, ALTER TABLE lab.orders ADD COLUMN c1 INT, ALGORITHM=INSTANT finished in 0.028 seconds. The readers didn&#39;t notice: the worst query took 36 ms, and throughput stayed at about 2,900 queries per second.</p><p>Then I added the blocker. Here is the same ALTER with one idle transaction open, reader throughput per half second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*9-i3Ku1qzLN4T_g2lQR7ZQ.png" /></figure><p>The moment the ALTER started, reads on the table stopped completely. Not slowed down: stopped. For 9.5 seconds, not one of the 16 readers completed a query. The processlist showed 17 sessions in Waiting for table metadata lock: the 16 readers plus the ALTER. When the blocker committed, the ALTER finished 0.04 seconds later, and every queued reader returned at once. The slowest of them had waited 10.049 seconds.</p><p>The transaction that caused all this had read a single row by primary key.</p><p>Sixteen threads with long-lived connections is the gentle version, because the pool caps how many sessions can pile up. Many applications open a connection per request instead: PHP, serverless functions, or a pool that grows under pressure. So I reran the experiment with an extra load that opens a new connection every 20 ms, runs one SELECT, and disconnects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8e9WhNI94alyfUjACo_hXA.png" /></figure><p>Connections climbed by about 50 a second, because nothing was finishing. Within about 3 seconds of the ALTER starting, Threads_connected hit 152 and the application started getting ERROR 1040: Too many connections. By the time the blocker committed, 363 connection attempts had been refused.</p><p>Note what the application team sees: a connection-limit error. Nothing in it mentions a lock, an ALTER, or an idle session. It’s easy to read it as a traffic spike. Raising max_connections mid-incident wouldn&#39;t fix anything either; by the same mechanism it would only give the queue more room to grow. I didn&#39;t test that last point, but nothing waiting on this lock can finish until the blocker ends.</p><p>One thing kept working: my monitoring session, which connects as root. Threads_connected peaked at 152 with max_connections=151 because mysqld permits max_connections + 1 connections, and the extra one is reserved for accounts with CONNECTION_ADMIN (<a href="https://dev.mysql.com/doc/refman/8.0/en/too-many-connections.html">Too many connections</a>). That reserved slot is how you get in to fix this, so make sure your application accounts don&#39;t have that privilege.</p><h3>Experiment 2: does “online” DDL avoid it?</h3><p>No. I ran the same setup with every ALTER style, and with variations on the blocker. Same 16 readers, same 10-second hold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*x1yzkQU8AwuSNq5W6tLsLA.png" /></figure><p>“Reads stopped for” counts half-second samples with zero completed queries, so it reads slightly under the 10-second hold.</p><p>ALGORITHM and LOCK describe what happens while the table is being changed. They say nothing about how the ALTER gets permission to start or finish. In all three styles, performance_schema.metadata_locks showed the same picture mid-freeze: the blocker holding a granted SHARED_READ, the ALTER holding a granted SHARED_UPGRADABLE (SHARED_NO_WRITE for COPY) plus a <strong>pending </strong><strong>EXCLUSIVE</strong>, and all 16 readers stuck on a pending SHARED_READ.</p><p>The INPLACE result surprised me a little. The manual describes an exclusive lock during execution as brief and limited to statement preparation, with the main upgrade at commit, so I half expected the index build to run first and the freeze to start later. In this test it didn’t: reads stopped within the first half-second of the ADD INDEX starting, and mid-freeze it was holding a pending EXCLUSIVE.</p><p>Isolation level didn’t matter either. A READ COMMITTED transaction still holds its metadata locks until it ends; isolation controls which row versions you see, not how long you hold the table.</p><p>The only blocker that didn’t cause a freeze was the autocommit one. Same session, same SELECT, same idle connection afterwards, but with no BEGIN the lock was released when the statement finished. That&#39;s rule 1 in action: an idle connection is harmless, an idle <em>transaction</em> isn&#39;t.</p><h3>Experiment 3: finding the blocker</h3><p>This is where real incidents lose the most time. Here is what each tool showed halfway through the freeze.</p><p><strong>SHOW PROCESSLIST</strong> shows the ALTER clearly, Waiting for table metadata lock, and 16 readers in the same state. The session actually responsible looks like this:</p><pre>ID  USER  COMMAND  TIME  STATE  INFO<br>26  app   Sleep    5            NULL</pre><p>It’s idle, with no query text. On a busy server with hundreds of sleeping pooled connections, it looks exactly like all the others.</p><p><strong>information_schema.INNODB_TRX</strong> narrows it down: thread 26 has a RUNNING transaction, 5 seconds old, with trx_query NULL. Useful, but it doesn&#39;t say which table that transaction touched, and on a real system there may be many open transactions.</p><p><strong>performance_schema.metadata_locks</strong> is the ground truth. Joined to performance_schema.threads to get processlist ids, it showed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*BIce2YskEeuGTmL3y7V8pA.png" /></figure><p>The blocker is the session that holds a <em>granted</em> lock on the table and isn’t the ALTER. The instrument behind this table, wait/lock/metadata/sql/mdl, was enabled by default on this 8.0.46 install.</p><p><strong>sys.schema_table_lock_waits</strong> is the view most runbooks recommend, and it&#39;s where you need to be careful. Mid-freeze it returned 34 rows, which summarise like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*WPYL2Neags9gQ9Icr0LlRQ.png" /></figure><p>Read literally, that picture is wrong in two ways. It lists SHARED_READ blocking SHARED_READ, which aren&#39;t conflicting lock types; the real blocker of the readers is the ALTER&#39;s pending EXCLUSIVE, which doesn&#39;t appear as a blocker at all. And it lists the ALTER (27) as a blocker on an equal footing with the idle transaction (26). From the output, the view seems to pair every pending lock with every granted lock on the same table, rather than with the one that actually conflicts. I haven&#39;t checked the view&#39;s source to confirm that, but the rows are consistent with it.</p><p>Either KILL does end the freeze, and I ran both. Killing the idle transaction (26) rolled it back; the ALTER completed 0.03 seconds later and the readers resumed. Killing the ALTER (27) released all 16 readers in the same half second, even though the idle transaction stayed open for another 3 seconds. Those are different decisions, though: one throws away the application&#39;s transaction, the other throws away your schema change. The view hands you both without saying which is the cause. The rows to act on are the ones where waiting_lock_type is EXCLUSIVE.</p><p>Finally, <strong>performance_schema.events_statements_history</strong> for the blocker&#39;s thread showed its last statements: BEGIN, then SELECT * FROM lab.orders WHERE id=1. That&#39;s how you find which code path left the transaction open, which matters more than the KILL.</p><h3>Experiment 4: a circuit breaker for your DDL</h3><p>The ALTER waits for its lock for lock_wait_timeout seconds, and the default is 31,536,000: one year (<a href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_lock_wait_timeout">server system variables</a>). In other words, by default the ALTER will hold the queue for as long as the idle transaction lives.</p><p>So I ran the same scenario with one extra line in the DDL session:</p><pre>SET SESSION lock_wait_timeout = 3;<br>ALTER TABLE lab.orders ADD COLUMN c1 INT, ALGORITHM=INSTANT;</pre><p>The ALTER gave up after 3.003 seconds with ERROR 1205: Lock wait timeout exceeded; try restarting transaction. Reads stopped for those 3 seconds, the worst reader waited 3.002 seconds, and then everything carried on normally while the idle transaction stayed open for another 7 seconds.</p><p>That’s the trade: a few seconds of stalled reads and a failed ALTER you retry later, instead of a stall that lasts as long as someone else’s forgotten transaction. The timeout bounds the damage; it doesn’t remove it. Every read on that table still waited up to 3 seconds, so pick a value your application’s own timeouts can absorb.</p><p>Two details from the manual are worth knowing. The timeout applies to each metadata lock attempt separately, so a statement that needs several locks can block for longer than the value before it errors. And it covers DDL, DML, LOCK TABLES, FLUSH TABLES WITH READ LOCK and LOCK INSTANCE FOR BACKUP, so it&#39;s also worth setting in backup and maintenance scripts.</p><h3>What I do about it now</h3><h3>Where idle transactions come from</h3><p>In the lab I opened the transaction deliberately. In production, nobody types BEGIN and walks away. The transaction usually comes from a driver default.</p><p>I checked one. A Python app using PyMySQL 2.2.8 with default settings, with no autocommit argument and no BEGIN anywhere, connects with @@session.autocommit = 0. After a single SELECT v FROM lab.t2 WHERE id=1, that connection had a RUNNING transaction in INNODB_TRX and a granted SHARED_READ metadata lock on the table. When I ran an ALTER against that table, it waited until its 4-second timeout and failed.</p><p>So a read-only request handler that never calls commit(), then hands its connection back to a pool, leaves exactly the blocker from Experiment 1. The server won&#39;t clean it up quickly either: wait_timeout was 28,800 seconds (8 hours) on this install. Check what your own drivers and pools default to; I only tested this one.</p><h3>Before running DDL</h3><ol><li><strong>Look for open transactions first.</strong> Anything old in information_schema.INNODB_TRX that has touched the table will block you. performance_schema.metadata_locks tells you which sessions hold a granted lock on that table right now.</li><li><strong>Always set a short lock wait on the DDL session.</strong> SET SESSION lock_wait_timeout = 3; (or whatever your application&#39;s timeouts can absorb), then retry the ALTER in a loop with a pause between attempts. A failed attempt costs a few seconds; a blocked one costs as long as the blocker lives.</li><li><strong>Remember that “online” doesn’t mean lock-free.</strong> INSTANT, INPLACE and LOCK=NONE all needed the exclusive lock in Experiment 2.</li></ol><h3>During the incident</h3><p>Run this query. It finds the sessions holding a granted lock on whatever table a pending exclusive lock (your DDL) is waiting for. In the lab it returned exactly one row: the idle session, with its transaction age.</p><pre>SELECT p.OBJECT_SCHEMA, p.OBJECT_NAME,<br>       pt.PROCESSLIST_ID      AS ddl_pid,<br>       gt.PROCESSLIST_ID      AS blocker_pid,<br>       g.LOCK_TYPE            AS blocker_lock,<br>       gt.PROCESSLIST_COMMAND AS blocker_command,<br>       TIMESTAMPDIFF(SECOND, trx.trx_started, NOW()) AS blocker_trx_age_s<br>FROM performance_schema.metadata_locks p<br>JOIN performance_schema.metadata_locks g<br>  ON g.OBJECT_TYPE = p.OBJECT_TYPE AND g.OBJECT_SCHEMA = p.OBJECT_SCHEMA<br> AND g.OBJECT_NAME = p.OBJECT_NAME<br> AND g.LOCK_STATUS = &#39;GRANTED&#39; AND g.OWNER_THREAD_ID &lt;&gt; p.OWNER_THREAD_ID<br>JOIN performance_schema.threads pt ON pt.THREAD_ID = p.OWNER_THREAD_ID<br>JOIN performance_schema.threads gt ON gt.THREAD_ID = g.OWNER_THREAD_ID<br>LEFT JOIN information_schema.INNODB_TRX trx ON trx.trx_mysql_thread_id = gt.PROCESSLIST_ID<br>WHERE p.LOCK_STATUS = &#39;PENDING&#39; AND p.LOCK_TYPE = &#39;EXCLUSIVE&#39;;</pre><p>Then decide what to kill. If the ALTER can wait, kill the ALTER: it’s your change, it’s safe to retry, and in Experiment 3 it released the readers immediately. Kill the blocker only when you know what its transaction was doing, because KILL rolls back whatever it had written. Either way, read its events_statements_history before it disappears. That&#39;s your only record of which code left the transaction open.</p><p>If the application is throwing Too many connections, get in through an account with CONNECTION_ADMIN. The reserved extra connection exists for exactly this.</p><h3>In application design</h3><p>For reads, use autocommit, or commit explicitly at the end of every request, including read-only ones. Keep transactions short and never hold one open across a network call, a user’s think time, or a message queue wait. If your framework returns connections to a pool, make sure it ends the transaction on return.</p><h3>What I didn’t prove</h3><ul><li><strong>One version.</strong> Everything ran on MySQL 8.0.46. The metadata-lock rules I cited have been in the manual for years, but I didn’t rerun this on 8.4 or 9.x.</li><li><strong>Small scale.</strong> 16 readers and one 200,000-row table on a 2-vCPU VM. The shape of the freeze shouldn’t depend on scale, since nothing can proceed until the lock clears, but the connection-storm timing depends on your arrival rate and max_connections.</li><li><strong>One driver.</strong> I tested PyMySQL’s default only. JDBC, Go’s database/sql, ORMs and pool libraries each have their own defaults. Check yours.</li><li><strong>The sys view’s internals.</strong> My reading of sys.schema_table_lock_waits comes from its output, not from its source.</li><li><strong>Online schema-change tools.</strong> gh-ost and pt-online-schema-change were out of scope. As far as I know, both still need a metadata lock for their final cut-over, so the same care applies, but I haven’t measured them.</li></ul><h3>Try it yourself</h3><p>The scripts are in the same companion repo as part 1: mdl_lab.py runs every scenario in this post (--scenario control | instant | inplace_index | copy | rc_blocker | autocommit_blocker | timeout | kill | kill_ddl | arrivals), and mdl_checks.py covers the PyMySQL default and the blocker query. The raw JSON output for every run is in results/mdl/.</p><p>Open question: the public GitHub URL for the scripts. Add it here before publishing.</p><p>Sources:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/metadata-locking.html">MySQL 8.0 Reference Manual: Metadata Locking</a> — lock duration within transactions, write-over-read priority</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-online-ddl-performance.html">MySQL 8.0 Reference Manual: Online DDL Performance and Concurrency</a> — DDL phases, exclusive lock at commit, pending lock blocking later transactions</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_lock_wait_timeout">MySQL 8.0 Reference Manual: server system variables, lock_wait_timeout</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/sys-schema-table-lock-waits.html">MySQL 8.0 Reference Manual: sys.schema_table_lock_waits</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/too-many-connections.html">MySQL 8.0 Reference Manual: Too many connections</a> — the reserved CONNECTION_ADMIN connection</li></ul><p><em>Next in MySQL Under Pressure: replication lag forensics, and why </em><em>Seconds_Behind_Source can mislead you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fefc1df0fe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Crashed MySQL 31 Times to See What It Really Loses]]></title>
            <link>https://yasharainduwara.medium.com/i-crashed-mysql-31-times-to-see-what-it-really-loses-378a40281221?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/378a40281221</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mysql-gtid-failover]]></category>
            <category><![CDATA[data-loss-protection]]></category>
            <category><![CDATA[innodb]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 16:44:13 GMT</pubDate>
            <atom:updated>2026-11-23T16:44:13.956Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MySQL Under Pressure, Part 1 <br>what innodb_flush_log_at_trx_commit and sync_binlog actually protect</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nzl3rzo7-Cn2BzX9F98Ueg.jpeg" /></figure><p>Ask ten DBAs what innodb_flush_log_at_trx_commit=2 costs you and most will say &quot;up to a second of data on a crash.&quot; That isn&#39;t wrong. It just isn&#39;t the whole story, and the missing parts are where incident reviews go sideways.</p><p>So I stopped arguing about it and measured. I set up MySQL 8.0.46 with a replica, ran a write workload, and killed mysqld 31 times across every combination of innodb_flush_log_at_trx_commit and sync_binlog. After each crash I compared three numbers: what the application had been told was committed, what InnoDB still had, and what the binary log had. In some runs I also checked a live replica.</p><p>A quick word on evidence, since this series stands or falls on it. When I say I measured something, the script and the raw output are in the repo linked at the end. When I quote the manual, I link the page. When I go beyond what I actually tested, I say so in the same sentence.</p><p><strong>The short version</strong></p><ul><li>On a mysqld crash, settings 1 and 2 lost nothing the client had been told was committed: zero in 12 out of 12 runs. Setting 2 is only exposed when the whole host goes down.</li><li>Setting 0 lost acknowledged commits in 10 of 12 runs. Usually just 0 to 5 rows, which looks harmless. Turn off one background thread (innodb_log_writer_threads) and it became 1,105 to 1,413 rows per crash.</li><li>Every lost transaction was still in the binary log. In the 9 runs where I checked, all 4,177 of them were also listed in gtid_executed. A replica ended up with 1,106 rows the source had lost. Both servers reported identical GTID sets, and replication didn&#39;t complain once.</li><li>MySQL 9.1 turned that thread off by default on machines with fewer than 32 logical CPUs. If 8.0 taught you that setting 0 “only loses a few rows”, that lesson won’t survive the upgrade.</li><li>A connection error on COMMIT doesn’t mean the transaction rolled back. In 3 of the 12 runs at settings 1 or 2, the row was safely on disk and the client never heard about it.</li></ul><h3>Why the usual answer isn’t good enough</h3><p>When a production database goes down hard, the post-incident review always asks two things. Did we lose anything we told the application was committed? And do the source and the replicas still agree?</p><p>Two settings decide the answer: innodb_flush_log_at_trx_commit for InnoDB&#39;s redo log and sync_binlog for the binary log. The usual one-liner, &quot;0 and 2 can lose about a second&quot;, skips three things that matter when you&#39;re designing a system. It treats a mysqld crash and a host crash as the same event. It says nothing about replicas. And it assumes defaults stay put between versions. They don&#39;t.</p><h3>What the manual actually promises</h3><p>Start with the source of truth. The <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_flush_log_at_trx_commit">InnoDB parameters page</a> describes the three values like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*ZUODBdCfdiQ1ThU7aMOnxg.png" /></figure><p>Two details are easy to miss. First, the once per second flush for 0 and 2 isn’t guaranteed. DDL and other internal InnoDB work can flush more often, and scheduling delays can make it less frequent. The interval comes from innodb_flush_log_at_timeout (default 1 second, maximum 2700).</p><p>Second, the manual just says “a crash”. It never separates mysqld dying from the operating system dying. That gap is exactly what my first experiment fills.</p><p>The <a href="https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_sync_binlog">binary logging page</a> covers sync_binlog:</p><ul><li>At 1 (the default), the binlog is synced before the transaction commits. If the host loses power, anything missing from the binlog was only <em>prepared</em>, and crash recovery rolls it back. InnoDB can’t end up with a transaction the binlog doesn’t have.</li><li>At 0, the OS decides when to flush. After a power cut or an OS crash, InnoDB may hold committed transactions the binlog never got.</li><li>At N, it syncs every N commit groups. Same risk as 0, just bounded by N.</li></ul><p>For a replicated setup, the manual recommends both at 1. It also warns that some disks and controllers report a flush as done when it isn’t. On that hardware, even 1 / 1 can’t protect you.</p><h3>How I tested it</h3><p>Everything ran in one environment, so read the timings as relative, not as numbers for your hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*vV9OlSCpOezyvQWdIKZsCw.png" /></figure><p>The single writer is what makes the counting exact. The client keeps the highest id whose INSERT came back OK. With one connection the ids have no gaps, so after recovery, acknowledged − COUNT(*) is precisely the number of acknowledged commits that disappeared.</p><p>I then decoded the binary log with mysqlbinlog -v. For every row the binlog had but the table didn&#39;t, I asked the server whether that transaction&#39;s GTID was in @@GLOBAL.gtid_executed.</p><p>SIGKILL stands in for the ways mysqld actually dies in production: the OOM killer, a segfault, an assertion, or a tired engineer with kill -9. The operating system keeps running, so anything already in the page cache survives. A power cut is a different event, and I deal with it separately in Experiment 3.</p><h3>Experiment 1: killing mysqld under every setting</h3><p>Only setting 0 lost acknowledged commits. sync_binlog made no difference at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*rN12wIUsBHj5ky-r-jaPoA.png" /></figure><p>Setting 2 is completely safe against a mysqld crash. It writes the redo to the OS at commit, and the OS outlives mysqld. That’s all there is to it.</p><p>sync_binlog doesn&#39;t matter here either. Even at 0, the binlog held every acknowledged transaction, because the write reaches the OS before the commit returns. sync_binlog only earns its cost when the OS itself goes down.</p><p>The interesting one is setting 0. The losses in the table are tiny, 0 to 5 rows, which surprised me given that the manual talks about a second’s worth. The reason is a design change in 8.0.11: dedicated log writer threads write redo from the log buffer to the OS in the background, independently of commit (<a href="https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/optimizing-innodb-logging.html">Optimizing InnoDB redo logging</a>). At my load they ran only a few commits behind.</p><p>When I switched those threads off, each crash lost 1,348 to 1,413 acknowledged commits. That’s roughly 0.6 seconds of this workload, which lines up with the documented once-per-second write. So the small number reflects how the threads happened to behave on my box. It isn’t something MySQL promises; the manual still documents about a second.</p><p>The extra binlog row in some of the 0 runs is a transaction that reached the binlog just before the kill, but whose OK never reached the client. It’s gone from InnoDB and present in the binlog.</p><p>One more detail, for whoever writes the application code. In 3 of the 12 runs at 1 or 2, the table had one more row than the client had been told about. The commit was durable; the OK packet just never arrived. A connection error on COMMIT means “I don’t know what happened”, not “it rolled back”. Retry that write blindly, without an idempotency key, and you’ve created a duplicate.</p><h3>Experiment 2: the replica that knows more than its source</h3><p>This is the result that changed how I think about setting 0.</p><p>I added a second 8.0.46 instance replicating with SOURCE_AUTO_POSITION=1, ran the same workload, killed the source and restarted it. Once the replica&#39;s gtid_executed covered everything the source claimed, I compared the two servers:</p><pre>settings              : innodb_flush_log_at_trx_commit=0 sync_binlog=1 extra=[&#39;--innodb-log-writer-threads=OFF&#39;]<br>client acknowledged   : 6426<br>source rows           : 5321<br>replica rows          : 6427<br>source gtid_executed  : 9697360a-e750-11f1-a6ad-02fc00000001:1-6431<br>replica gtid_executed : 9697360a-e750-11f1-a6ad-02fc00000001:1-6431<br>GTID sets identical   : True<br>CHECKSUM TABLE src/rep: 2658478917 / 3960539817<br>ids on replica only   : [5322, 5323, 5324, 5325, 5326, 5327, 5328, 5329, 5330, 5331] ... (1106 rows)<br>replica IO/SQL errors : &#39;&#39; / &#39;&#39;</pre><p>The source lost 1,105 rows the client had been told were committed. The replica has all of them, plus one transaction whose OK never arrived: 1,106 rows that exist only on the replica. The checksums differ. Yet both servers report exactly the same GTID set, and replication shows no error.</p><p>The control run at setting 1 came out identical on every measure. A setting-0 run with the writer threads at their default happened to lose nothing that time; Experiment 1 tells us that’s luck, not safety.</p><p>This is worse than the row count suggests. The source’s gtid_executed claims every one of those missing transactions. Auto-positioning, failover managers and any health check that compares GTID sets will call these two servers consistent. Only a comparison of the actual data caught it; I used CHECKSUM TABLE.</p><p>It also flips the usual assumption about which copy to trust. The replica holds what the application was told is committed. If the old source carries on as primary after recovery, you’re running on the copy that lost data.</p><p>I’d expect this to surface again later. If the application ever re-inserts one of those primary keys on the source, the replica already has it, and with row-based replication the applier would stop on a duplicate-key error days after the real cause. I didn’t reproduce that last step, so treat it as reasoning, not measurement.</p><h3>Experiment 3: what actually reaches disk, and what that means for a power cut</h3><p>I couldn’t safely cut power in this environment, so I measured the thing that decides the outcome instead: which commits were fsynced before the client got its OK. I attached strace -f -y to mysqld during 1,000 single-row commits per setting and matched every fsync and fdatasync to the file it hit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*re4d9lKMKxPeVnyf0Oiy5Q.png" /></figure><p>Counts are per 1,000 commits. I left out doublewrite, undo and data-file syncs: they show up at every setting from background page flushing and aren’t on the commit path. At 2 / 1 there were also two syncs for redo file management (#ib_redoN_tmp and the #innodb_redo directory), which I didn&#39;t count.</p><p>Look at setting 2: five redo fsyncs for a thousand acknowledged commits. No commit waited for its redo to reach disk. Every one was acknowledged while its redo sat in the page cache.</p><p>The Innodb_os_log_fsyncs status counter tells the same story from a separate run: 3,665 to 3,771 redo fsyncs per 3,000 commits at setting 1, against 3 to 13 at 0 or 2. The two methods disagree on absolute numbers. strace saw about 1.8 to 1.9 per commit at setting 1, the counter about 1.2 to 1.3, and I haven&#39;t reconciled that. They agree on what matters: at least one redo fsync per commit at 1, almost none at 0 or 2.</p><p>Now apply that to a host crash. This part is reasoning from these measurements and the manual, not something I reproduced:</p><ul><li>At 2 / 1, the binlog is on disk and up to about a second of redo isn’t. After a power cut, the binlog, and every replica that read it, can be ahead of InnoDB. That’s the same silent divergence as Experiment 2, arriving by a different route.</li><li>At 2 / 0 or 0 / 0, neither log is safe at commit, and the two can lose different amounts. The source might be missing transactions its replicas have, or hold ones its own binlog never recorded.</li><li>At 1 / 1, both are on disk before the OK, and the manual’s recovery rule applies: anything missing from the binlog was only prepared, so it’s rolled back.</li></ul><p>Here’s what that safety cost on my VM, measured without strace, on one connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*cIX1-yr83qWxyZPSHdMLdw.png" /></figure><p>Those are single-connection numbers on one VM disk. Under real concurrency, binary log group commit syncs once per commit group rather than once per transaction (<a href="https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_binlog_group_commit_sync_delay">binary logging options</a>). The gap narrows, and the ratios won’t transfer to your hardware.</p><h3>The upgrade trap</h3><p>This is the part that worried me most. MySQL 9.1 changed the default of innodb_log_writer_threads to OFF on systems with fewer than 32 logical processors (<a href="https://dev.mysql.com/doc/relnotes/mysql/9.1/en/news-9-1-0.html">9.1.0 release notes</a>). The 8.4 LTS manual still lists ON, with no CPU condition (<a href="https://dev.mysql.com/doc/refman/8.4/en/innodb-parameters.html#sysvar_innodb_log_writer_threads">InnoDB parameters, 8.4</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*-KykD5zE63wH8wcHscSgWg.png" /></figure><p>Plenty of database hosts have fewer than 32 logical CPUs; my lab VM had 2. Picture a server that has run setting 0 on 8.0 or 8.4 for years and never visibly lost much. Upgrade it to 9.x on the same box and it falls back to the documented one-second window, without anyone touching my.cnf. Experiment 1&#39;s OFF row, 1,348 to 1,413 commits per crash, shows the scale.</p><p>To be precise: I reproduced this by switching the threads off on 8.0.46, not by running 9.x. The exact numbers on 9.x are an expectation, not a measurement.</p><p>The lesson I take from it is to design to what the manual promises, not to what you’ve happened to observe. Check what you’re really running with SELECT @@innodb_log_writer_threads, @@innodb_flush_log_at_trx_commit, @@sync_binlog;, and check again after every upgrade. That upgrade is coming for most of us anyway: MySQL 8.0 reached end of life in April 2026 (<a href="https://www.openlogic.com/blog/mysql-8-end-of-life">OpenLogic</a>).</p><h3>So what should you run?</h3><p>My position, based on everything above: 1 / 1 for any system of record, and for any replication source you can’t rebuild. Everything else is a trade-off, and trade-offs belong in writing, where the next person on call will find them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*yzB4_b6po-f4mMejBpZQ4w.png" /></figure><p>Two things outside MySQL still decide whether any of this holds. Does your storage actually honour fsync? The manual itself warns that some disks and controllers acknowledge flushes they haven’t done. And does your failover tooling compare data, or only GTID sets?</p><h3>After a hard crash: what I’d check</h3><p>If a source running anything other than 1 / 1 went down uncleanly, assume the source and replicas disagree until the data proves otherwise.</p><ol><li><strong>Find the settings at the time of the crash, not today’s.</strong> Read my.cnf, and check performance_schema.persisted_variables for anything changed with SET PERSIST.</li><li><strong>Read the recovery lines in the error log.</strong> In the lab, every restart logged Starting XA crash recovery... followed by XA crash recovery finished.</li><li><strong>Don’t take matching GTID sets as proof.</strong> In Experiment 2 they matched exactly while 1,106 rows differed.</li><li><strong>Compare the data on tables written around the crash.</strong> Use CHECKSUM TABLE on a quiet table, as I did in the lab, or <a href="https://docs.percona.com/percona-toolkit/pt-table-checksum.html">pt-table-checksum</a> for a live, chunked comparison through replication.</li><li><strong>Decide which side is the truth.</strong> A replica that received the binlog usually holds what the application was told is committed, as in Experiment 2.</li><li><strong>Reconcile the “outcome unknown” commits in the application.</strong> Clients that got a connection error on COMMIT should check by idempotency key before they retry.</li></ol><h3>What I didn’t prove</h3><p>I’d rather point out the edges of this work myself, since readers at this level will find them anyway.</p><ul><li><strong>I didn’t cut the power.</strong> Experiment 3 shows what was unsynced at the moment of commit. What a real power cut does to that data is reasoning, not observation. A filesystem that can drop unsynced writes on demand, such as LazyFS, would turn that reasoning into a reproduction.</li><li><strong>One writer, one host, one build.</strong> Under heavy concurrency, group commit and writer-thread lag behave differently. Don’t expect the 0–5 row loss at setting 0 to hold at every load.</li><li><strong>I didn’t run 9.x.</strong> The 9.1 default change is documented. I reproduced its effect by switching the threads off on 8.0.46.</li><li><strong>I trusted the disk.</strong> Every result assumes the VM’s storage honoured fsync. I didn’t test storage that lies about it.</li></ul><h3>Try it yourself</h3><p>Every table in this post comes from the scripts in the companion repo: lab.py (Experiments 1 and 3), replica_test.py (Experiment 2) and strace_by_file.sh (the fsync breakdown). The raw output files are there too. If your numbers come out different, I&#39;d genuinely like to see them.</p><p>Open question: the public GitHub URL for the scripts. Add it here before publishing.</p><p>Sources:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html">MySQL 8.0 Reference Manual: InnoDB startup options and system variables</a> — innodb_flush_log_at_trx_commit, innodb_flush_log_at_timeout, innodb_log_writer_threads</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html">MySQL 8.0 Reference Manual: binary logging options and variables</a> — sync_binlog, group commit</li><li><a href="https://dev.mysql.com/doc/refman/8.4/en/innodb-parameters.html">MySQL 8.4 Reference Manual: InnoDB startup options and system variables</a> — 8.4 default of innodb_log_writer_threads</li><li><a href="https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/optimizing-innodb-logging.html">MySQL 8.0 Reference Manual: Optimizing InnoDB redo logging</a> — dedicated log writer threads since 8.0.11, configurable since 8.0.22</li><li><a href="https://dev.mysql.com/doc/relnotes/mysql/9.1/en/news-9-1-0.html">MySQL 9.1.0 release notes</a> — innodb_log_writer_threads default change (WL #16396)</li><li><a href="https://docs.percona.com/percona-toolkit/pt-table-checksum.html">Percona Toolkit: pt-table-checksum</a></li><li><a href="https://www.openlogic.com/blog/mysql-8-end-of-life">OpenLogic: MySQL 8.0 end of life</a> — 8.0 EOL, April 2026</li></ul><p><em>Next in MySQL Under Pressure: metadata lock pile-ups, or how one idle transaction and an </em><em>ALTER TABLE can freeze a table.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=378a40281221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing IBM API Connect on Red Hat OpenShift]]></title>
            <link>https://yasharainduwara.medium.com/installing-ibm-api-connect-on-red-hat-openshift-984f8dc04916?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/984f8dc04916</guid>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[red-hat]]></category>
            <category><![CDATA[api-management]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 13:48:27 GMT</pubDate>
            <atom:updated>2026-09-25T13:50:37.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8Hvh6Jbb3qbQyNDCI_y5w.jpeg" /></figure><p>IBM API Connect (APIC) runs on OpenShift as a set of operator-managed subsystems, and a clean install comes down to four things:<br>Block storage, the IBM operators, a cert manager, and one top level custom resource.</p><h3>Overview and prerequisites</h3><p>IBM API Connect is a platform for creating, securing, managing, and monitoring APIs. Red Hat OpenShift Container Platform (OCP) is the hybrid cloud foundation it runs on here, with each API Connect subsystem (Management, Developer Portal, Gateway, and Analytics) deployed and managed by operators.</p><p>Before you start, have the following ready:</p><ul><li>An OCP cluster on version 4.12.7, ideally 3 master nodes (8 vCPU, 16 GB RAM each) and 3 worker nodes (16 vCPU, 32 GB RAM each).</li><li>Permissions to install and configure software in the cluster.</li><li>An IBMid, used to obtain the entitlement key for IBM’s container registry.</li><li>A storage orchestrator that provides a block storage class. This article uses Rook-Ceph.</li></ul><h3>Step 1: Install Rook Ceph for block storage</h3><p>API Connect needs a block storage class. Rook-Ceph is an open source, cloud native storage orchestrator for Kubernetes and provides one. Run the following from a workstation with oc access to the cluster.</p><pre>yum install git -y<br>git clone https://github.com/rook/rook.git<br>cd rook/deploy/examples</pre><pre>oc create -f crds.yaml<br>oc create -f common.yaml<br>oc create -f operator-openshift.yaml<br># verify: oc get all -n rook-ceph  (pods should be Running, not ContainerCreating)</pre><pre>oc create -f cluster.yaml<br># verify: oc get pod -n rook-ceph  (rook-ceph-mon* and rook-ceph-osd* must be Running)</pre><pre>oc create -f ./csi/rbd/storageclass.yaml<br># verify: oc get sc  (rook-ceph-block should exist)<br>oc create -f ./csi/rbd/pvc.yaml</pre><pre>oc create -f filesystem.yaml<br>oc create -f ./csi/cephfs/storageclass.yaml<br>oc create -f ./csi/cephfs/pvc.yaml</pre><pre>oc create -f toolbox.yaml<br># verify: the rook-ceph-osd-prepare-node* pods show Completed</pre><p>Then make Rook Ceph the default storage class, so API Connect’s persistent volume claims bind to it without extra configuration:</p><pre>oc patch storageclass &lt;storage class name&gt; -p &#39;{&quot;metadata&quot;: {&quot;annotations&quot;:{&quot;storageclass.kubernetes.io/is-default-class&quot;:&quot;true&quot;}}}&#39;</pre><p>Do not move on until the mon and OSD pods are healthy. Every later step depends on this storage layer.</p><h3>Step 2: Install the API Connect operator</h3><h3>Prepare the namespace and pull secret</h3><ol><li>Get your entitlement key: log in to the IBM Container Library with your IBMid and, under “Access your container software”, click <strong>Copy key</strong>.</li><li>Create a namespace for API Connect:</li></ol><pre>oc create ns &lt;APIC-namespace&gt;</pre><p>3. If you are installing the operator into a single namespace, create an OperatorGroup. Skip this if you install into all namespaces, because openshift-operators you already have one. Save this as apiconnect-operator-group.yaml. It scopes the operator&#39;s role-based access control (RBAC) to that namespace.</p><pre>apiVersion: operators.coreos.com/v1<br>kind: OperatorGroup<br>metadata:<br>  name: &lt;operator-group-name&gt;<br>  namespace: &lt;APIC-namespace&gt;<br>spec:<br>  targetNamespaces:<br>  - &lt;APIC-namespace&gt;</pre><pre>oc apply -f apiconnect-operator-group.yaml</pre><p>4. In the OpenShift web console, go to <strong>Workloads &gt; Secrets</strong>, confirm the project is your API Connect namespace, and choose <strong>Create &gt; Image pull secret</strong> with these values:</p><blockquote>Secret name:ibm-entitlement-key</blockquote><blockquote>Authentication type:Image registry credentials</blockquote><blockquote>Registry server address: cp.icr.io</blockquote><blockquote>Username: cp</blockquote><blockquote>Password: The entitlement key you copied</blockquote><h3>Add the catalog source</h3><p>Click <strong>+</strong> in the console banner to open Import YAML, paste this definition and click <strong>Create</strong>:</p><pre>apiVersion: operators.coreos.com/v1alpha1<br>kind: CatalogSource<br>metadata:<br>  name: opencloud-operators<br>  namespace: openshift-marketplace<br>spec:<br>  displayName: IBMCS Operators<br>  publisher: IBM<br>  sourceType: grpc<br>  image: quay.io/opencloudio/ibm-common-service-catalog:latest<br>  updateStrategy:<br>    registryPoll:<br>      interval: 45m</pre><p>The subscriptions below reference a catalog named ibm-operator-catalog. Confirm that the catalog source exists in openshift-marketplace (oc get catalogsource -n openshift-marketplace) and add IBM&#39;s operator catalog if it does not, or the subscriptions will not resolve.</p><h3>Subscribe to API Connect</h3><p>Save this asapic-sub.yaml, set the namespace, and apply it:</p><pre>apiVersion: operators.coreos.com/v1alpha1<br>kind: Subscription<br>metadata:<br>  name: ibm-apiconnect<br>  namespace: &lt;namespace&gt;<br>spec:<br>  channel: v3.3<br>  name: ibm-apiconnect<br>  source: ibm-operator-catalog<br>  sourceNamespace: openshift-marketplace</pre><pre>oc apply -f apic-sub.yaml</pre><p>In the console, open <strong>Operators &gt; Installed Operators</strong> with <strong>All Projects</strong> selected. If an operator such as ibm-apiconnect or ibm-cert-manager-operator shows &quot;Upgrade available&quot;, click it, choose <strong>Preview InstallPlan</strong>, then <strong>Approve</strong>. Wait for the IBM API Connect and IBM DataPower Gateway operators to finish installing, and keep the DataPower operator, because API Connect requires it.</p><h3>Check IBM Cloud Pak foundational services</h3><p>Confirm that the ibm-common-services-operator subscription exists. If it does not, save this as common-services-sub.yaml and apply it:</p><pre>apiVersion: operators.coreos.com/v1alpha1<br>kind: Subscription<br>metadata:<br>  name: ibm-common-service-operator<br>  namespace: &lt;namespace&gt;<br>spec:<br>  channel: &lt;channel&gt;<br>  name: ibm-common-service-operator<br>  source: ibm-operator-catalog<br>  sourceNamespace: openshift-marketplace</pre><p>Use openshift-operators as the namespace to install for all namespaces, or the namespace you created earlier for a single-namespace install. For the channel, use v3.23 if you follow the continuous delivery (CD) stream of foundational services, or the matching long-term service release (LTSR) channel if you follow that stream.</p><pre>oc apply -f common-services-sub.yaml</pre><p>Wait until IBM Cloud Pak foundational services, IBM NamespaceScope, and the Operand Deployment Lifecycle Manager operators have been installed.</p><h3>Install the cert manager</h3><p>Save this as cert-manager-operand-request.yaml:</p><pre>apiVersion: operator.ibm.com/v1alpha1<br>kind: OperandRequest<br>metadata:<br>  name: ibm-apiconnect-cert-manager<br>  namespace: &lt;namespace&gt;<br>spec:<br>  requests:<br>  - operands:<br>    - name: ibm-cert-manager-operator<br>    registry: common-service<br>    registryNamespace: ibm-common-services</pre><pre>oc apply -f cert-manager-operand-request.yaml</pre><p>Wait until the IBM Cert Manager operator reports as installed before continuing.</p><h3>Step 3: Deploy and verify API Connect</h3><h3>Create the API Connect cluster</h3><ol><li>In the console, go to <strong>Operators &gt; Installed Operators</strong> and click the <strong>IBM API Connect</strong> operator.</li><li>On the <strong>API Connect cluster</strong> tile, click <strong>Create Instance</strong>. This creates the top-level custom resource, which in turn deploys the four subsystems: Management, Developer Portal, Gateway and Analytics.</li><li>Fill in the form parameters for your environment, such as the profile, storage class and endpoints, and create the instance.</li></ol><h3>Verify the installation</h3><p>Check that the cluster reports as healthy:</p><pre>oc get apic -n &lt;APIC-namespace&gt;</pre><p>List the routes to find the Cloud Manager endpoint. Look for the one ending in mgmt-admin-apic:</p><pre>oc get routes -n &lt;APIC-namespace&gt;</pre><p>Open that endpoint to reach the Cloud Manager UI and log in as admin. When you install with the top-level CR, the admin password is generated for you. Retrieve it from the secret:</p><pre>oc get secret -n &lt;APIC-namespace&gt; | grep mgmt-admin-pass<br>oc get secret -n &lt;APIC-namespace&gt; &lt;secret_name_from_previous_command&gt; -o jsonpath=&quot;{.data.password}&quot; | base64 -d &amp;&amp; echo &quot;&quot;</pre><p>Once you are in Cloud Manager, you can set up provider organizations and API Managers, then create products and publish them.</p><h3>Things to watch for</h3><ul><li><strong>Storage first.</strong> If the Rook-Ceph mon or OSD pods are not healthy, API Connect’s persistent volume claims will sit in Pending.</li><li><strong>Catalog names must match.</strong> The subscriptions point at ibm-operator-catalog, so that catalog source has to exist in openshift-marketplace.</li><li><strong>Approve pending upgrades.</strong> An operator stuck on “Upgrade available” can block dependent operators from finishing.</li><li><strong>Keep the DataPower operator.</strong> API Connect’s Gateway subsystem depends on it.</li><li><strong>Sizing.</strong> The node sizes in the prerequisites are a starting point. Size for your production API traffic before go-live.</li></ul><p>Following these steps gives you API Connect running on Red Hat OpenShift with Cloud Manager ready for provider organizations, products, and published APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984f8dc04916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Production DB2 Databases from AIX to RHEL When Backup/Restore Is Impossible]]></title>
            <link>https://yasharainduwara.medium.com/migrating-production-db2-databases-from-aix-to-rhel-when-backup-restore-is-impossible-e19a13580718?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19a13580718</guid>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 20:59:43 GMT</pubDate>
            <atom:updated>2026-07-03T20:59:43.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-q6amVMopBb7atnZADBZw.png" /></figure><blockquote>A field guide from a cross endian migration of a banking FileNet and Business Automation Workflow estate with the commands, the failure modes, and the mistakes I’ll never make twice</blockquote><p>Every DB2 DBA knows the standard migration play: BACKUP DATABASE on the old server, RESTORE DATABASE on the new one, roll forward, hand over to the application team. Fast, proven, preserves everything.</p><p>It also doesn’t work when you’re leaving AIX for Linux on x86 and that’s a scenario more and more of us are facing as organizations retire IBM Power estates.</p><p>IBM Power servers running AIX are <strong>big-endian</strong>. Intel/AMD servers running RHEL are <strong>little-endian</strong>. DB2 backup images are not portable across that boundary; a cross-endian restore is simply unsupported. When the bank I work with decided to move its entire IBM FileNet Content Manager, IBM Content Navigator, and IBM Business Automation Workflow stack off AIX, we faced <strong>10 production databases, </strong>the FileNet Global Configuration Database, multiple object stores, the Navigator database, BAW process and task databases, and Case Manager databases with no backup/restore path available.</p><p>The only supported route: <strong>db2look</strong> to extract DDL, <strong>db2move</strong> to export and reload the data, one table at a time, for every database. Including one content object store with roughly <strong>2 billion rows</strong>, ~220 GB allocated, and a <strong>700+ GB IXF export footprint</strong>.</p><p>This is the long version of what we learned the version I wish had existed before we started. Everything below is anonymized; the lessons are not.</p><h3>Phase 0: Why db2look + db2move, and What That Actually Implies</h3><p>It’s worth being precise about what this method does and doesn’t carry, because it shapes the entire project:</p><p><strong>What travels:</strong></p><ul><li>Table and index <em>definitions</em> (via db2look DDL)</li><li>Row data (via db2move EXPORT → IXF files → db2move LOAD)</li><li>Grants and authorization statements (via db2look, <em>if</em> you extract them deliberately)</li></ul><p><strong>What does not travel:</strong></p><ul><li>Physical page layout, free space, fragmentation</li><li>Index <em>data </em>indexes are rebuilt from their definitions during LOAD</li><li>Catalog statistics (until you run RUNSTATS on the target)</li><li>Recovery history the target database is born with no past</li><li>Instance and database configuration, unless you extract and replay it explicitly (db2look -d &lt;DB&gt; -f -x)</li></ul><p>Two consequences follow immediately. First, <strong>the target database is a new design decision, not a copy </strong>every creation-time choice is back on the table. Second, <strong>your validation strategy cannot rely on comparing sizes or catalog statistics </strong>more on that below.</p><h3>Phase 1: Pre-Flight - The Authority Model Is Part of the Migration</h3><p>Our first db2look run against a FileNet database produced a beautifully formatted DDL file containing headers and nothing else. No tables, no indexes, no error. Just silence.</p><p>The root cause: <strong>FileNet’s installer revokes PUBLIC EXECUTE on DB2’s monitoring routines</strong> as part of its security hardening. db2look depends on those routines to enumerate database objects. When it can’t call them, it doesn’t fail loudly it produces an empty script and exits cleanly. In an automated pipeline, that empty script would have sailed straight into the target build.</p><p>The fix became a mandatory pre-flight step for <strong>every</strong> database:</p><pre>-- Who actually holds what, in THIS database?<br>SELECT GRANTEE, DBADMAUTH, SECURITYADMAUTH, DATAACCESSAUTH, ACCESSCTRLAUTH<br>FROM SYSCAT.DBAUTH;</pre><p>Never assume two databases in the same instance share an authority model. Ours didn’t: on the AIX source, one ID held SECADM/DBADM/ACCESSCTRL while a <em>different</em> ID had SYSADM via OS group membership (SYSADM_GROUP in the DBM CFG). That asymmetry exists because SYSADM is granted <strong>only</strong> through OS group membership, while SECADM and DBADM require explicit SQL grants per database. It has to be understood and deliberately re-established on the target not blindly copied, and never discovered mid-export.</p><p>One more authority trap: the exporting user needs <strong>DATAACCESS on the database</strong>, or db2move EXPORT dies with SQL3020N part way through. Grant it up front.</p><p>A smaller but real db2look gotcha on AIX: pointing -o at a directory that doesn&#39;t exist produces a segfault rather than a friendly error. Create output directories with absolute paths first.</p><p><strong>Architect takeaway:</strong> for any middleware managed database FileNet, WebSphere, SAP the security catalog is part of the migration scope. You are not just moving data, you are moving an authority model, and the middleware vendor may have quietly customized it.</p><h3>Phase 2: Designing the Target Databases</h3><p>Because each target database is created from scratch, get these right <em>before</em> the first LOAD:</p><p><strong>Page size.</strong> FileNet on RHEL requires databases created with <strong>PAGESIZE 32768</strong>. This is a creation-time property get it wrong and you’re dropping and recreating the database after the application refuses to start. (And note it’s the <em>page size</em> that’s the hard requirement here, not the codepage, which is a separate consideration.)</p><p><strong>Logging design.</strong> Three parameters, decided on day one:</p><pre>UPDATE DB CFG FOR &lt;DB&gt; USING LOGARCHMETH1 DISK:/path/to/archlogs<br>UPDATE DB CFG FOR &lt;DB&gt; USING OVERFLOWLOGPATH /path/to/overflowlogs<br>UPDATE DB CFG FOR &lt;DB&gt; USING LOGINDEXBUILD ON</pre><p>LOGARCHMETH1 applies online with no downtime. OVERFLOWLOGPATH is non negotiable if HADR is in your future. And LOGINDEXBUILD ON matters <em>before</em> the load, not after. Without it, every index built during the migration arrives on your future HADR standbys marked <strong>INVALID</strong>, and you discover it at the worst possible moment after a takeover.</p><p><strong>Expect the target to be smaller - much smaller.</strong> Our largest object store shrank from ~766 GB allocated on AIX to under 500 GB on RHEL. Nothing was lost. What didn’t make the trip: years of accumulated fragmentation, free pages, deleted row space, and overallocated index extents. db2move carries rows; db2look carries index <em>definitions</em>, which are rebuilt cleanly and compactly during LOAD. If your stakeholders see the size delta and panic, this paragraph is for them.</p><h3>Phase 3: db2move at Scale - The Sharp Edges</h3><p>Moving billions of rows taught us things the documentation states quietly or not at all.</p><h3>Run it from the right directory</h3><p>db2move &lt;DB&gt; LOAD must execute from the directory containing db2move.lst and the .ixf files. It resolves them relative to the working directory. Obvious in hindsight; a wasted evening in practice.</p><h3>Use NONRECOVERABLE, always, at this scale</h3><pre>db2move &lt;DB&gt; LOAD -lo NONRECOVERABLE</pre><p>A recoverable LOAD of a multi hundred gigabyte table will hit <strong>SQL0964C</strong> (log full) no matter how generously you size active logs. NONRECOVERABLE bypasses data page logging entirely. The trade off the table can’t be rolled forward through is irrelevant here; the freshly built database has no recovery history worth preserving. Take a full offline backup immediately after the load completes, and <em>that</em> becomes recovery point zero.</p><h3>The bind phase looks exactly like a hang</h3><p>After the data phase, db2move rebinds packages. On a large catalog, this ran <strong>~40 minutes with zero visible progress,</strong> no growing files, no obvious activity. It is not frozen. Which brings me to the most expensive lesson of the project.</p><h3>Never force applications mid LOAD</h3><p>During one run that appeared stalled, a force application was issued against what turned out to be a healthy in flight LOAD. A killed LOAD on a NONRECOVERABLE table does not roll back gracefully. It left the database in a state that required a <strong>full drop and recreate cycle</strong> of a 200+ GB database days of work, repeated.</p><p>The bitter irony: db2move on restart <strong>reads its own </strong><strong>.msg files and skips tables that already completed</strong>. A controlled, patient restart loses almost nothing. An impatient kill loses everything. If you suspect a hang, diagnose first:</p><pre>db2pd -utilities              # is the LOAD utility actually progressing?<br>db2pd -db &lt;DB&gt; -load          # load phase detail</pre><p>…and check MON_GET_CONNECTION / MON_CURRENT_SQL before you touch anything.</p><h3>The infinite retry loop that wasn’t a filesystem problem</h3><p>One LOAD spun in an endless retry loop while df showed plenty of free space. The filesystem wasn&#39;t full the <strong>tablespace containers</strong> were. DMS/automatic-storage free pages, not OS free space, is the resource LOAD consumes. db2pd -utilities plus a free-pages check on the data tablespace diagnoses this in seconds once you know to look:</p><pre>SELECT TBSP_NAME, TBSP_FREE_PAGES, TBSP_USED_PAGES, TBSP_TOTAL_PAGES<br>FROM TABLE(MON_GET_TABLESPACE(&#39;&#39;, -1));</pre><h3>Respect the source platform’s quirks</h3><p>Our AIX scripting assumptions kept biting:</p><ul><li>No watchuse while :; do ...; sleep 5; done loops</li><li>No date +%s use perl for epoch timestamps</li><li>No du -sh / du -sg it&#39;s du -sk and arithmetic</li><li>grep alternation needs the -E flag</li><li>And one memorable morning discovering that a script edited in Notepad++ on Windows had shipped <strong>carriage returns</strong> onto AIX, breaking every line</li></ul><p>None of these are exotic. All of them cost time at 2 a.m.</p><h3>Phase 4: Validation - The Golden Baseline</h3><p>Our acceptance gate was simple and absolute: <strong>a direct </strong><strong>SELECT COUNT(*) row count per table, captured at export time on AIX, compared against the same count on RHEL after load.</strong> ~2 billion rows on the largest database, matched exactly.</p><p>Two things we explicitly ruled out as validation methods:</p><ul><li><strong>SYSCAT.TABLES.CARD</strong>it&#39;s a statistic, stale by definition until RUNSTATS runs on the target, and worthless as evidence.</li><li><strong>Size comparison</strong> meaningless across the endian boundary for the fragmentation reasons above.</li></ul><p>Run RUNSTATS <em>after</em> validation passes, then take your baseline backup. In a regulated banking environment, that golden-count spreadsheet is also your audit artifact the thing you show when someone asks, two years later, how you know nothing was lost.</p><h3>Phase 5: The Second Migration - HADR Across Four Nodes</h3><p>Loading the data was half the project. The target architecture was, per database:</p><ul><li><strong>Primary</strong> (production data center)</li><li><strong>Principal standby</strong>, SYNC mode, same data center the zero data loss failover partner</li><li><strong>Two auxiliary standbys</strong>, SUPERASYNC mode, at the DR site</li><li><strong>Pacemaker automation</strong> split across two cluster domains, managed exclusively through IBM’s <strong>db2cm</strong> tooling</li></ul><p>Multiply by 10 databases and you also get a VIP address planning exercise: two VIPs per database per cluster domain, <strong>40 VIP addresses total</strong>, all of which must sit on the same subnet as the physical nodes for gratuitous ARP to work during failover. That’s a network-team conversation you want to have in week one, not week ten.</p><p>Hard-won HADR specifics:</p><p><strong>Standby initialization demands an offline backup.</strong> An online backup embeds log-chain dependencies that prevent the standby from landing in the ROLLFORWARD PENDING state HADR requires. The sequence is rigid:</p><pre># On primary<br>db2 deactivate database &lt;DB&gt;<br>db2 backup database &lt;DB&gt; to /backup        # OFFLINE<br>db2 activate database &lt;DB&gt;</pre><pre># On each standby, after restore<br>db2 restore database &lt;DB&gt; from /backup taken at &lt;timestamp&gt;<br>db2inidb &lt;DB&gt; as standby                    # not optional<br>db2 start hadr on database &lt;DB&gt; as standby</pre><p><strong>HADR_TARGET_LIST is a primary-side concern</strong>, and multiple standbys sharing a port number across different hostnames is fully valid per IBM a topology detail the samples don&#39;t make obvious.</p><p><strong>You can start HADR on a live primary.</strong> db2 start hadr on database &lt;DB&gt; as primary by force works against an active production database without a deactivation window. In a bank, avoiding an outage window is worth knowing this cold.</p><p><strong>SUPERASYNC standbys never reach PEER.</strong> REMOTE_CATCHUP <em>is</em> their steady state. We burned hours early on “fixing” a DR standby that was already perfectly healthy. Monitor with:</p><pre>SELECT HADR_ROLE, HADR_STATE, HADR_SYNCMODE, STANDBY_ID,<br>       HADR_CONNECT_STATUS, HADR_LOG_GAP<br>FROM TABLE(MON_GET_HADR(NULL));</pre><p><strong>Spool limits are a trade off, not a fix.</strong> When DR-link congestion back pressured the primary, setting HADR_SPOOL_LIMIT -1 (unlimited) on the SUPERASYNC nodes unblocked production immediately. But unlimited spooling trades a blocked primary for <strong>disk exhaustion risk on the standby and an extended recovery window at takeover</strong> the standby has to replay everything it spooled. We treated -1 as a tactical unblock and moved to a bounded, calculated value sized from log-generation rate and available standby disk.</p><p><strong>Verify name resolution obsessively.</strong> A one-character hostname typo replicated across /etc/hosts on four nodes produced HADR connection failures that masqueraded, for hours, as a network problem. getent hosts &lt;name&gt; On every node, both directions belong in the pre flight checklist. (The eventual fix was a one-line sedthe diagnosis was the expensive part.)</p><p><strong>db2cm, never raw pcs/crm.</strong> DB2’s Pacemaker integration owns its resource model. Manipulating cluster resources directly with pcs or crm behind db2cm’s back produces configurations db2cm can neither validate nor repair. One tool, exclusively.</p><p>We also kept an IBM Severity 1 support case open in parallel for the thornier HADR startup errors (SQL1768N family). In a regulated environment, IBM’s fingerprints on the resolution matter for the audit trail as much as for the fix.</p><h3>Phase 6: What Made It Survivable - Process</h3><ol><li><strong>Golden row count baseline</strong> per table as the non negotiable acceptance gate.</li><li><strong>Per-database authority audit</strong> (SYSCAT.DBAUTH) before any extraction now a permanent standard in our runbooks.</li><li><strong>Runbooks for the failure paths</strong>, not just the happy path: what a stalled LOAD looks like versus a genuinely hung one, what a restart safely skips, when drop/recreate is truly required.</li><li><strong>One database proven end to end</strong> export, load, validate, HADR on all four nodes, failover test before parallelizing the remaining nine.</li><li><strong>No improvising on production.</strong> Every tempting “quick fix” went through the same scrutiny as a planned change. The one time urgency won the mid-LOAD force it cost a full rebuild. That incident is now the first page of the runbook.</li></ol><p>Cross-endian DB2 migrations are rare enough that most DBAs will do at most one in a career, and common enough given the pace of AIX to Linux consolidation that more of us will face them than expect to. The tooling is old and unglamorous, and it is absolutely capable of moving billions of rows reliably, <em>provided</em> you respect its assumptions: authority models verified, directories correct, NONRECOVERABLE at scale, offline backups for standby seeding, and above all, patience during the phases that look like hangs but aren’t.</p><p>If you’re planning one: budget more time for the security model, validation gates, and runbooks than for the data movement itself.</p><p>The bytes are the easy part.</p><p><em>I’m a production DB2 database administrator working with IBM FileNet, Business Automation Workflow, and multi node HADR environments on AIX and RHEL. Views are my own; all environment details in this article have been anonymized. If you’re facing a similar migration, I’d genuinely like to hear how yours went the comments are open.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19a13580718" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Tuning Is Not Guesswork, It’s Engineering]]></title>
            <link>https://yasharainduwara.medium.com/database-tuning-is-not-guesswork-its-engineering-75ef20e4173c?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ef20e4173c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[microsoft-sqlserver]]></category>
            <category><![CDATA[dba]]></category>
            <category><![CDATA[database-performance]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 14:52:10 GMT</pubDate>
            <atom:updated>2025-12-08T14:52:10.380Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, I was called in by a client who reported a serious performance issue. Their on-prem MSSQL Server (with over 32 CPUs) was hitting 90%+ CPU utilization, and the connected business application was slowing to a crawl.</p><p>At first glance, a high CPU might appear to be a database problem. Still, the real challenge is determining whether the issue is actually within SQL Server or somewhere else in the ecosystem (application, network, or hardware layer).</p><p>Here’s how I approached it step by step:</p><ol><li><strong>Verified the source of CPU load</strong><br>• Checked Task Manager and PerfMon to confirm sqlservr.exe was consuming the majority of CPU.<br>• Ran test queries directly in SSMS. If they ran fast locally but slow via the app, it hinted at app or network bottlenecks.</li><li><strong>Analyzed SQL workload</strong><br>• Used DMVs (sys.dm_exec_query_stats, sys.dm_exec_requests) to find the top CPU consuming queries.<br>• Reviewed execution plans to identify table scans, missing indexes, and parallelism overhead.<br>• Used Query Store and Activity Monitor to visualize query trends and CPU patterns.</li><li><strong>Optimized the database</strong><br>• Updated outdated statistics (sp_updatestats) for accurate query plans.<br>• Created missing indexes suggested by the optimizer.<br>• Rewrote non-SARGable queries and resolved parameter sniffing issues using OPTION(RECOMPILE) and query hints.<br>• Verified configuration: MAXDOP, Cost Threshold for Parallelism, and power plan set to High Performance.</li><li><strong>Collaborated across teams</strong><br>• Checked with the application team for chatty query patterns (too many repetitive calls).<br>• Worked with network engineers to ensure latency and throughput were not limiting performance.<br>• Shared findings transparently so every team could take ownership of their layer.</li></ol><blockquote>📈 The result? After applying targeted indexing and query tuning, the CPU utilization dropped from 90% to around 65%, and the application response times improved 1–2×.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYCk4SqFvJ34xahv" /></figure><p><strong>This reinforced a critical lesson: </strong><br>Database performance tuning is both an art and a science, but also a team sport.</p><blockquote>If you’re managing on-prem SQL workloads and seeing high CPU, start with structured diagnosis, don’t guess.</blockquote><blockquote><strong>Measure</strong>, <strong>isolate</strong>, <strong>tune</strong>, and then <strong>monitor</strong>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ef20e4173c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do Most Companies Still Use Oracle as Their Core Database?]]></title>
            <link>https://yasharainduwara.medium.com/why-do-most-companies-still-use-oracle-as-their-core-database-ba7615ee6651?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba7615ee6651</guid>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[oracle-database]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 14:36:35 GMT</pubDate>
            <atom:updated>2025-12-01T14:36:35.331Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in my first year at university, I kept asking myself this question. Oracle is known for being complex to manage, expensive due to licensing, and sometimes overwhelming in terms of operational complexity. So why do most banks, governments, and large enterprises still trust Oracle as their core production database?</p><p>I received the answer this week while studying for my final year exam. Here are the big reasons for that 👇</p><p><strong>1. Real Application Clusters (RAC)<br></strong>👉 <em>The only true active-active clustering at the database engine level. No failover tricks. All nodes are live, scaling linearly across servers.</em></p><p><strong>2. Cache Fusion Technology<br></strong>👉 <em>Unique to Oracle: memory blocks are shared across RAC nodes in real time, giving global cache consistency without waiting on disk I/O.</em></p><p><strong>3. Flashback Technology<br></strong>👉 <em>Like time travel for your data. You can query rows as of 5 minutes ago, recover dropped tables, or rewind the database without restoring backups.</em></p><p><strong>4. Active Data Guard<br></strong>👉<em> Standby databases aren’t idle. They can serve read queries, apply redo in real time, and offload backups. High availability + reporting in one.</em></p><p><strong>5. Application Continuity &amp; Transaction Guard<br></strong>👉 <em>If a node fails mid-transaction, Oracle replays it safely, guaranteeing no duplicates and no half-commits.</em></p><p><strong>6. Deadlock Prevention &amp; Concurrency Design<br></strong>👉 <em>Oracle identifies and removes most deadlocks by design with row-level locking and MVCC. It also detects and resolves conflicts instantly, enabling massive concurrency without messy code workarounds.</em></p><p><strong>7. Edition-Based Redefinition (EBR)<br></strong>👉 <em>Upgrade schemas with zero downtime. You can run two versions of application code objects in parallel during a live upgrade.</em></p><p><strong>8. Security at the Kernel Level<br></strong>👉 <em>Beyond TDE, Oracle offers Virtual Private Database, Label Security, and Data Redaction. That&#39;s why it is trusted by governments, defense, and banks. (Yes, you can even hide sensitive data from your own vendors.)</em></p><p><strong>9. Exadata + Smart Scan <br></strong>👉<em>SQL Server and Db2 speed up analytics, but they still process data in the DB engine. Oracle Exadata is different. It pushes SQL processing into storage, so heavy queries scale with the storage tier, not just the DB node.</em></p><p>That’s why, despite the cost and complexity, Oracle remains the major choice for mission-critical systems where downtime or data loss is not an option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dvVpOBu_uxYwBV-p" /></figure><blockquote>💡 Summary <br>Oracle is not always the easiest, but it’s often the safest bet when you need absolute reliability.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7615ee6651" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Your Database Understand the Meaning of Data?]]></title>
            <link>https://yasharainduwara.medium.com/does-your-database-understand-the-meaning-of-data-1cb9838a55ac?source=rss-2ff90c913782------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb9838a55ac</guid>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Yashara Induwara]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 14:32:05 GMT</pubDate>
            <atom:updated>2025-11-24T14:32:05.620Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day, I was running some routine queries, and everything appeared to be fine. I was searching for terms in our database, and I felt like I was in control.</p><p>Until I wasn’t,</p><p>I typed in “dog” 🐶 -&gt; the search returned dog. Perfect!<br>Then I tried “wolf” 🐺 -&gt; nothing. A big, fat zero.</p><p>My mind raced. How could the system not understand that a “wolf” is fundamentally related to a “dog”? I know, it’s a simple example, but in a world of endless data and complex relationships, this is a real problem. My database was blind to meaning. It only understood exact letters, forcing me to manually build a web of synonyms, one tedious connection at a time.</p><p>That’s when I found Oracle Vector Search in 23ai. And it was a revelation.</p><p>Instead of matching letters, this system works with embeddings. It transforms words, images, and even user behavior into vectors, geometric representations of their meaning. Suddenly, “dog” and “wolf” weren’t just two different words; they were neighbors in a vibrant, intelligent vector space because the AI model encoded their semantic similarity.</p><p>I tried it on my workload, and the difference was night and day. Searches became smarter, recommendations felt intuitive, and anomalies that would have been hidden for days popped out instantly.</p><p>This was my aha! moment. 🎉<br>Databases are not just about rows and columns anymore. We’ve gone from punch cards to relational, to object-oriented, and now to something truly revolutionary. A database that understands the world the way we do.</p><p>📢 Dear DB enthusiasts, get your packs ready. <br>The next chapter of data is here, and it’s finally starting to make sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb9838a55ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>