{
  "version": "https://jsonfeed.org/version/1.1",
  "title": "Muhammet Şafak — Engineering",
  "home_page_url": "https://muhammetsafak.com/engineering/",
  "feed_url": "https://muhammetsafak.com/engineering/feed.json",
  "description": "Production lessons, architecture decisions, database, server and application patterns, and AI-assisted engineering: notes, system write-ups, essays and developer tools that run in your browser.",
  "language": "en-US",
  "authors": [
    {
      "name": "Muhammet Şafak",
      "url": "https://muhammetsafak.com"
    }
  ],
  "items": [
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-rollout-one-way-doors/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-rollout-one-way-doors/",
      "title": "Upgrade Rollout and the One-Way Doors",
      "summary": "A gradual rollout does not make an upgrade reversible. Image tags, traffic share and config roll back; schema and data, serialized state and external contracts do not. Split every one-way door into expand, migrate and contract, and write down the proof you need before crossing each step.",
      "content_html": "<p>You can pull back a traffic share; you cannot pull back a written row.</p>\n<p>That is why a gradual rollout does not make an upgrade reversible. Martin Fowler’s canary release opens the new version to a small set of users first, which means two versions are live at the same time. If both write to the same database, the data has to work with both. When the share is pulled back, the rows the new version wrote stay where they are.</p>\n<p><a href=\"https://muhammetsafak.com/engineering/notes/upgrade-prerequisites/\">Part 5</a> had you write the evidence for four gates and sent nothing to production. Now we send. Keep two separate questions in mind: in what order do we go out, and which step can we not undo once we have?</p>\n<h2 id=\"a-rollout-is-a-sequence\">A Rollout Is a Sequence</h2>\n<p>Write the sequence as four stops: staging, a small share, a growing share, everything. Next to each stop, write two things.</p>\n<p>The first is the rollback cost: how much work, how much time and who is involved in returning to the state before this stop? The second is the stop criterion: which observation pauses the rollout or starts the rollback? Write the criterion before the rollout, not during it. A “let’s watch a bit longer” decided under pressure is not a criterion.</p>\n<p>The number in the criterion is per system. This article cannot tell you which error rate or which latency is enough to stop, and the same goes for the traffic share percentages. What I can say is that the number has to be written before the rollout starts, and its owner is known: the name of the person who makes the stop decision sits next to the number.</p>\n<p>Amazon’s 2016 shareholder letter splits decisions in two: <a href=\"https://www.aboutamazon.com/news/company-news/2016-letter-to-shareholders\">many are reversible, “two-way doors”</a>. In this article “one-way door” is my own term: a step after which going back is blocked not by the code you write but by freshly written data or a promise made to the outside. For reversible doors, moving fast is enough. For the others you have to slow down, and the shape of slowing down is below.</p>\n<p>As you write the rollback cost for each stop, one will come out non-zero, perhaps infinite.</p>\n<h2 id=\"which-step-cannot-be-undone\">Which Step Cannot Be Undone</h2>\n<p>The reversible ones are easy: image tag, traffic share, config. Gate 4 in Part 5 showed it: the previous image can be pulled and the previous lock is at hand. The irreversible ones sit where data and promises are:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Door</th><th>Reversible?</th><th>Proof before crossing</th></tr></thead><tbody><tr><td>Image tag, traffic share, config</td><td>Yes: the previous tag and values are at hand</td><td>The rollback record from Part 5</td></tr><tr><td>Schema and data migration</td><td>The structure partly; the data no</td><td>A staging record where <code>down</code> was run and the data checked afterwards</td></tr><tr><td>Serialized state: queue payload, cache, session</td><td>If the new version wrote it, the old version may not be able to read it</td><td>A staging run showing the old version reading a record the new version wrote</td></tr><tr><td>External contract: API response, webhook, event payload, signed token</td><td>No, if a consumer acted on it</td><td>A contract test or consumer sign-off showing the old and new shapes are both valid</td></tr></tbody></table></div>\n<p>Let us open the rows in order.</p>\n<p><strong>Schema and data migration.</strong> <a href=\"https://laravel.com/docs/12.x/migrations\">The Laravel documentation</a> asks the <code>down</code> method of a migration to reverse the operations of <code>up</code>; it also says some migration operations are destructive, may cause you to lose data, and ask for confirmation before running in production. The conclusion that follows is my reasoning, not the documentation’s: <code>down</code> rebuilds the structure, not the data. Adding a column back does not bring the deleted values back. If the new version wrote to that column and <code>down</code> drops it, what was written is gone.</p>\n<p><strong>Serialized state.</strong> A record written to a queue, a cache or a session outlives your code. PHP’s <a href=\"https://www.php.net/manual/en/function.unserialize.php\"><code>unserialize</code> documentation</a> says an object whose class has no definition comes back as <code>__PHP_Incomplete_Class</code>. If the new version renamed or removed a class and you go back to the old version, the same can happen in the other direction. <a href=\"https://laravel.com/docs/12.x/queues\">Laravel workers are long-lived</a> processes; they do not see a code change until they are restarted, and <code>queue:restart</code> exists for that. If two versions process the same queue for a while, which one wrote the payload decides the outcome.</p>\n<p><strong>External contract.</strong> A field in an API response, a webhook body, the schema of an event payload, the contents of a signed token: these live outside your code. If a consumer has acted on the new shape, rolling back the image does not roll back what the consumer did. I cite no primary source for this row; it is reasoning. You know which consumers your system has.</p>\n<p>The three rows share something: the rollback is tested not in your code but in something that has become permanent or sits in someone else’s hands. So the proof column shows that thing, not the code: a rollback run on staging, an old record that was read, a contract test that passed. “The code looks right” does not count as proof.</p>\n<h2 id=\"split-the-door\">Split the Door</h2>\n<p>Do not cross a one-way door in a single step. Fowler’s ParallelChange pattern has three phases: expand, migrate, contract.</p>\n<ul>\n<li><strong>Expand:</strong> add the new shape, do not delete the old one. A column is added, the old column stays. Both versions work.</li>\n<li><strong>Migrate:</strong> move consumers and data to the new shape. While both shapes are valid, every step is reversible.</li>\n<li><strong>Contract:</strong> remove the old shape.</li>\n</ul>\n<p>For a rollout the consequence is this: three phases become three separate deploys. Expand is safe for both the new and the old version; if you roll the image back, the old version still works. Contract is the real one-way door and happens after the rollback window has closed. The window is your definition: the moment the new version carries all the traffic and you decide you will not return to the old one.</p>\n<p>Let us state the cost plainly. You need at least one extra deploy, and in the in-between period the code carries two shapes at once: it writes to both the old and new column, reads both the old and new payload. That code is temporary, but temporary code that is forgotten becomes permanent. The expiry condition: when the contract step is done, the in-between code is deleted. Write the name and the date of whoever will do the contract next to the in-between code.</p>\n<p>The same pattern works for serialized state: first let the new version read both shapes, then change which version writes, and only last stop reading the old shape.</p>\n<h2 id=\"rector-dry-run\">Rector Dry-Run</h2>\n<p>A code change can be a door too. If upgrading the runtime (in the example, from 8.2 to 8.4) and adapting the code to the target happen in the same deploy, you cannot tell which one is responsible when something breaks.</p>\n<p><a href=\"https://github.com/rectorphp/rector\">Rector</a> transforms code automatically. <code>vendor/bin/rector src --dry-run</code> does not apply the change; it shows it as a diff. An example: PHP 8.4 <a href=\"https://www.php.net/manual/en/migration84.deprecated.php\">deprecates</a> a typed parameter with a <code>null</code> default (<code>string $name = null</code>) and asks for <code>?string $name = null</code>. I am not claiming here which Rector rule makes this transformation; if you see this line in the diff, you read what changed.</p>\n<p>What matters about this transformation is that it is also valid on the old runtime. So ship it as its own deploy, before the runtime change. That leaves the runtime change alone, and a reversible step.</p>\n<p>The question the dry-run does not answer: is the transformation actually valid on the old runtime? The diff does not say. The suite running on your current image does; Part 5’s baseline exists for exactly this. The dry-run is for seeing the diff; the suite is the proof of safety.</p>\n<h2 id=\"the-plan-page\">The Plan Page</h2>\n<p>Write the rollout plan on one page:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 2\"><table><thead><tr><th>Step</th><th>Rollback cost</th><th>Stop criterion</th><th>Proof before crossing</th></tr></thead><tbody><tr><td>Rector transformation (valid on the old runtime)</td><td>Go back to the old image</td><td>Suite red, error rate over the threshold</td><td>Green suite on the current image</td></tr><tr><td>Runtime change, staging</td><td>Previous tag</td><td>Suite red on staging</td><td>Suite output on the target image</td></tr><tr><td>Small share</td><td>Reset the share</td><td>The threshold written in advance</td><td>The staging record</td></tr><tr><td>Expand</td><td>Previous image; the new column stays</td><td>The old version errors on the new shape</td><td>A run where the old version reads the new shape</td></tr><tr><td>Migrate</td><td>Write the data back to the old shape</td><td>An inconsistency is found</td><td>A check showing both shapes are equal</td></tr><tr><td>Contract</td><td>None</td><td>Only once the rollback window has closed</td><td>A record that the window closed, and an owner for deleting the in-between code</td></tr></tbody></table></div>\n<p>Fill in the numeric thresholds yourself. The word “None” in the contract row is not a mistake, it is a marker: that row is your one-way door.</p>\n<blockquote><p><strong>Tan:</strong> The column I would compare most closely in the table is the distance between rollback cost and the proof required before crossing. The higher the cost, the heavier the proof, and writing it once is not enough; it has to be read again whenever the door changes. If the team paying for the in-between period is not the team that will do the contract step, put an expiry date for the interim code on one person's name.</p></blockquote>\n<h2 id=\"where-this-framework-stops\">Where This Framework Stops</h2>\n<p>The table shows the order and the doors; it does not give you thresholds, traffic share percentages or the length of the in-between period. Those are your system’s answers: which error rate stops the rollout, in how many steps the share grows, when the rollback window closes.</p>\n<p>Tool choice (feature flag product, deployment tool, traffic routing) is out of scope; the logic of the doors is independent of the tool. The external contract row is reasoning, not a sourced fact; review your own consumers. The Fowler pages are not pinned to a version number; read the Laravel and PHP documentation for the version you run.</p>\n<p>Who decides, who is on call and who signs off is the subject of Part 7. The cases where not upgrading at all is legitimate belong to <span data-scheduled=\"/engineering/essays/deciding-not-to-upgrade/\">Part 8</span>.</p>\n<h2 id=\"the-door-you-cannot-pull-the-row-back-through\">The Door You Cannot Pull the Row Back Through</h2>\n<p>Back to the opening line: which step in your plan is the door where you cannot pull back the written row?</p>\n<p>Write your rollout plan. Add the rollback cost and the stop criterion to every step; for every one-way door, write the proof you will show before crossing.</p>",
      "content_text": "> **TL;DR:** A gradual rollout does not make an upgrade reversible. Image tags, traffic share and config roll back; schema and data, serialized state and external contracts do not. Split every one-way door into expand, migrate and contract, and write down the proof you need before crossing each step.\n\nYou can pull back a traffic share; you cannot pull back a written row.\n\nThat is why a gradual rollout does not make an upgrade reversible. Martin Fowler's canary release opens the new version to a small set of users first, which means two versions are live at the same time. If both write to the same database, the data has to work with both. When the share is pulled back, the rows the new version wrote stay where they are.\n\n[Part 5](/engineering/notes/upgrade-prerequisites/) had you write the evidence for four gates and sent nothing to production. Now we send. Keep two separate questions in mind: in what order do we go out, and which step can we not undo once we have?\n\n## A Rollout Is a Sequence\n\nWrite the sequence as four stops: staging, a small share, a growing share, everything. Next to each stop, write two things.\n\nThe first is the rollback cost: how much work, how much time and who is involved in returning to the state before this stop? The second is the stop criterion: which observation pauses the rollout or starts the rollback? Write the criterion before the rollout, not during it. A \"let's watch a bit longer\" decided under pressure is not a criterion.\n\nThe number in the criterion is per system. This article cannot tell you which error rate or which latency is enough to stop, and the same goes for the traffic share percentages. What I can say is that the number has to be written before the rollout starts, and its owner is known: the name of the person who makes the stop decision sits next to the number.\n\nAmazon's 2016 shareholder letter splits decisions in two: [many are reversible, \"two-way doors\"](https://www.aboutamazon.com/news/company-news/2016-letter-to-shareholders). In this article \"one-way door\" is my own term: a step after which going back is blocked not by the code you write but by freshly written data or a promise made to the outside. For reversible doors, moving fast is enough. For the others you have to slow down, and the shape of slowing down is below.\n\nAs you write the rollback cost for each stop, one will come out non-zero, perhaps infinite.\n\n## Which Step Cannot Be Undone\n\nThe reversible ones are easy: image tag, traffic share, config. Gate 4 in Part 5 showed it: the previous image can be pulled and the previous lock is at hand. The irreversible ones sit where data and promises are:\n\n| Door | Reversible? | Proof before crossing |\n|---|---|---|\n| Image tag, traffic share, config | Yes: the previous tag and values are at hand | The rollback record from Part 5 |\n| Schema and data migration | The structure partly; the data no | A staging record where `down` was run and the data checked afterwards |\n| Serialized state: queue payload, cache, session | If the new version wrote it, the old version may not be able to read it | A staging run showing the old version reading a record the new version wrote |\n| External contract: API response, webhook, event payload, signed token | No, if a consumer acted on it | A contract test or consumer sign-off showing the old and new shapes are both valid |\n\nLet us open the rows in order.\n\n**Schema and data migration.** [The Laravel documentation](https://laravel.com/docs/12.x/migrations) asks the `down` method of a migration to reverse the operations of `up`; it also says some migration operations are destructive, may cause you to lose data, and ask for confirmation before running in production. The conclusion that follows is my reasoning, not the documentation's: `down` rebuilds the structure, not the data. Adding a column back does not bring the deleted values back. If the new version wrote to that column and `down` drops it, what was written is gone.\n\n**Serialized state.** A record written to a queue, a cache or a session outlives your code. PHP's [`unserialize` documentation](https://www.php.net/manual/en/function.unserialize.php) says an object whose class has no definition comes back as `__PHP_Incomplete_Class`. If the new version renamed or removed a class and you go back to the old version, the same can happen in the other direction. [Laravel workers are long-lived](https://laravel.com/docs/12.x/queues) processes; they do not see a code change until they are restarted, and `queue:restart` exists for that. If two versions process the same queue for a while, which one wrote the payload decides the outcome.\n\n**External contract.** A field in an API response, a webhook body, the schema of an event payload, the contents of a signed token: these live outside your code. If a consumer has acted on the new shape, rolling back the image does not roll back what the consumer did. I cite no primary source for this row; it is reasoning. You know which consumers your system has.\n\nThe three rows share something: the rollback is tested not in your code but in something that has become permanent or sits in someone else's hands. So the proof column shows that thing, not the code: a rollback run on staging, an old record that was read, a contract test that passed. \"The code looks right\" does not count as proof.\n\n## Split the Door\n\nDo not cross a one-way door in a single step. Fowler's ParallelChange pattern has three phases: expand, migrate, contract.\n\n- **Expand:** add the new shape, do not delete the old one. A column is added, the old column stays. Both versions work.\n- **Migrate:** move consumers and data to the new shape. While both shapes are valid, every step is reversible.\n- **Contract:** remove the old shape.\n\nFor a rollout the consequence is this: three phases become three separate deploys. Expand is safe for both the new and the old version; if you roll the image back, the old version still works. Contract is the real one-way door and happens after the rollback window has closed. The window is your definition: the moment the new version carries all the traffic and you decide you will not return to the old one.\n\nLet us state the cost plainly. You need at least one extra deploy, and in the in-between period the code carries two shapes at once: it writes to both the old and new column, reads both the old and new payload. That code is temporary, but temporary code that is forgotten becomes permanent. The expiry condition: when the contract step is done, the in-between code is deleted. Write the name and the date of whoever will do the contract next to the in-between code.\n\nThe same pattern works for serialized state: first let the new version read both shapes, then change which version writes, and only last stop reading the old shape.\n\n## Rector Dry-Run\n\nA code change can be a door too. If upgrading the runtime (in the example, from 8.2 to 8.4) and adapting the code to the target happen in the same deploy, you cannot tell which one is responsible when something breaks.\n\n[Rector](https://github.com/rectorphp/rector) transforms code automatically. `vendor/bin/rector src --dry-run` does not apply the change; it shows it as a diff. An example: PHP 8.4 [deprecates](https://www.php.net/manual/en/migration84.deprecated.php) a typed parameter with a `null` default (`string $name = null`) and asks for `?string $name = null`. I am not claiming here which Rector rule makes this transformation; if you see this line in the diff, you read what changed.\n\nWhat matters about this transformation is that it is also valid on the old runtime. So ship it as its own deploy, before the runtime change. That leaves the runtime change alone, and a reversible step.\n\nThe question the dry-run does not answer: is the transformation actually valid on the old runtime? The diff does not say. The suite running on your current image does; Part 5's baseline exists for exactly this. The dry-run is for seeing the diff; the suite is the proof of safety.\n\n## The Plan Page\n\nWrite the rollout plan on one page:\n\n| Step | Rollback cost | Stop criterion | Proof before crossing |\n|---|---|---|---|\n| Rector transformation (valid on the old runtime) | Go back to the old image | Suite red, error rate over the threshold | Green suite on the current image |\n| Runtime change, staging | Previous tag | Suite red on staging | Suite output on the target image |\n| Small share | Reset the share | The threshold written in advance | The staging record |\n| Expand | Previous image; the new column stays | The old version errors on the new shape | A run where the old version reads the new shape |\n| Migrate | Write the data back to the old shape | An inconsistency is found | A check showing both shapes are equal |\n| Contract | None | Only once the rollback window has closed | A record that the window closed, and an owner for deleting the in-between code |\n\nFill in the numeric thresholds yourself. The word \"None\" in the contract row is not a mistake, it is a marker: that row is your one-way door.\n\n\n> **Tan:** The column I would compare most closely in the table is the distance between rollback cost and the proof required before crossing. The higher the cost, the heavier the proof, and writing it once is not enough; it has to be read again whenever the door changes. If the team paying for the in-between period is not the team that will do the contract step, put an expiry date for the interim code on one person's name.\n\n\n## Where This Framework Stops\n\nThe table shows the order and the doors; it does not give you thresholds, traffic share percentages or the length of the in-between period. Those are your system's answers: which error rate stops the rollout, in how many steps the share grows, when the rollback window closes.\n\nTool choice (feature flag product, deployment tool, traffic routing) is out of scope; the logic of the doors is independent of the tool. The external contract row is reasoning, not a sourced fact; review your own consumers. The Fowler pages are not pinned to a version number; read the Laravel and PHP documentation for the version you run.\n\nWho decides, who is on call and who signs off is the subject of Part 7. The cases where not upgrading at all is legitimate belong to Part 8.\n\n## The Door You Cannot Pull the Row Back Through\n\nBack to the opening line: which step in your plan is the door where you cannot pull back the written row?\n\nWrite your rollout plan. Add the rollback cost and the stop criterion to every step; for every one-way door, write the proof you will show before crossing.\n\n## Sources\n\n- [Database: Migrations (Laravel 12.x)](https://laravel.com/docs/12.x/migrations) — Laravel\n- [Queues (Laravel 12.x)](https://laravel.com/docs/12.x/queues) — Laravel\n- [unserialize](https://www.php.net/manual/en/function.unserialize.php) — PHP\n- [Deprecated Features (PHP 8.4)](https://www.php.net/manual/en/migration84.deprecated.php) — PHP\n- [rectorphp/rector](https://github.com/rectorphp/rector) — Rector\n- [2016 Letter to Shareholders](https://www.aboutamazon.com/news/company-news/2016-letter-to-shareholders) — Amazon",
      "date_published": "2026-11-29T00:00:00.000Z",
      "tags": [
        "deployment",
        "database",
        "decisions",
        "production",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/code-review-culture/",
      "url": "https://muhammetsafak.com/engineering/essays/code-review-culture/",
      "title": "Code Review: Dropping Syntax, Looking at Architecture",
      "summary": "Reviewer attention is limited and flows to the first formatting inconsistency it meets, so formatters, linters and static analysis should be enforced in CI and humans should be left only the questions a tool cannot answer: does the code belong here, is there a simpler design, was the failure path considered. A small PR is actually read; on a large PR the important points get missed and the approval is a formality.",
      "content_html": "<p>One pull request had thirty comments. Twenty-eight were about formatting and naming: this whitespace, that variable name, a comma over there. The remaining two touched on logic. The real question that should have been asked — “does this code belong here” — was never asked at all.</p>\n<p>A good code review is not an argument about commas. But reviews, left to themselves, drift exactly there.</p>\n<h2 id=\"human-attention-is-expensive\">Human attention is expensive</h2>\n<p>A reviewer’s attention is a limited resource. There’s only so much focus they can spend on a PR, and that focus flows to the first thing they see.</p>\n<p>If the first thing they see is a formatting inconsistency, attention goes there — and nothing is left for design, architecture, or failure scenarios. Small, easily noticed problems overshadow large, important questions. This is the bikeshed effect: the trivial topic everyone has an opinion on gets ahead of the important topic no one can fully evaluate.</p>\n<h2 id=\"automate-what-can-be-automated\">Automate what can be automated</h2>\n<p>The fix is simple: nothing a human doesn’t need to look at should reach a human.</p>\n<ul>\n<li>Formatting is left to a formatter — it’s not even up for debate; the tool decides.</li>\n<li>Style and simple errors are left to a linter and static analysis (PHPStan, Psalm).</li>\n<li>These are enforced in CI; non-compliant code never even reaches review.</li>\n</ul>\n<p>If a formatting comment was written, the setup is incomplete. With the right setup, that debate isn’t even <strong>possible</strong>.</p>\n<h2 id=\"the-questions-a-human-should-ask\">The questions a human should ask</h2>\n<p>Once the tools have done the cleanup, the real review remains. The questions a human reviewer should ask:</p>\n<ul>\n<li>Is this code in the right place? Does it cross a module boundary without permission? As I said in <a href=\"https://muhammetsafak.com/engineering/essays/why-i-start-with-a-modular-monolith/\">the modular monolith post</a>, this is the most important question to ask in review.</li>\n<li>Is there a simpler design? Does this change add <a href=\"https://muhammetsafak.com/engineering/essays/signals-of-an-over-complex-system/\">unnecessary complexity</a> to the system?</li>\n<li>What happens when this code fails? Has the failure path been thought through?</li>\n<li>Does this name carry the right concept? Naming — the part a formatter can’t solve, the part that genuinely belongs to a human.</li>\n</ul>\n<p>These can’t be automated; that’s exactly why they’re a human’s job.</p>\n<h2 id=\"a-review-is-a-conversation-not-a-gate\">A review is a conversation, not a gate</h2>\n<p>Code review is not gatekeeping. Its purpose isn’t only to catch bugs; it’s knowledge sharing. The reviewer learns the code, the author gains another perspective, the team converges on a shared standard.</p>\n<p>That’s why tone matters: “why did you do this this way” should be a real question, not an accusation. A good review culture is one where the author doesn’t go on the defensive.</p>\n<h2 id=\"small-prs\">Small PRs</h2>\n<p>One last practical point: big PRs don’t get a real review. No one can look deeply at an eight-hundred-line change; the result is an “LGTM” and a token approval. Small PRs, on the other hand, actually get read. Keeping the PR small is a precondition for a good review.</p>\n<hr/>\n<p>The value of a code review is not in the comma it catches but in the design question it asks. Hand everything that can be automated to the tools; leave the human only what a human can answer.</p>\n<p>Let the linter look at syntax; you look at architecture.</p>",
      "content_text": "> **TL;DR:** Reviewer attention is limited and flows to the first formatting inconsistency it meets, so formatters, linters and static analysis should be enforced in CI and humans should be left only the questions a tool cannot answer: does the code belong here, is there a simpler design, was the failure path considered. A small PR is actually read; on a large PR the important points get missed and the approval is a formality.\n\nOne pull request had thirty comments. Twenty-eight were about formatting and naming: this whitespace, that variable name, a comma over there. The remaining two touched on logic. The real question that should have been asked — \"does this code belong here\" — was never asked at all.\n\nA good code review is not an argument about commas. But reviews, left to themselves, drift exactly there.\n\n## Human attention is expensive\n\nA reviewer's attention is a limited resource. There's only so much focus they can spend on a PR, and that focus flows to the first thing they see.\n\nIf the first thing they see is a formatting inconsistency, attention goes there — and nothing is left for design, architecture, or failure scenarios. Small, easily noticed problems overshadow large, important questions. This is the bikeshed effect: the trivial topic everyone has an opinion on gets ahead of the important topic no one can fully evaluate.\n\n## Automate what can be automated\n\nThe fix is simple: nothing a human doesn't need to look at should reach a human.\n\n- Formatting is left to a formatter — it's not even up for debate; the tool decides.\n- Style and simple errors are left to a linter and static analysis (PHPStan, Psalm).\n- These are enforced in CI; non-compliant code never even reaches review.\n\nIf a formatting comment was written, the setup is incomplete. With the right setup, that debate isn't even **possible**.\n\n## The questions a human should ask\n\nOnce the tools have done the cleanup, the real review remains. The questions a human reviewer should ask:\n\n- Is this code in the right place? Does it cross a module boundary without permission? As I said in [the modular monolith post](/engineering/essays/why-i-start-with-a-modular-monolith/), this is the most important question to ask in review.\n- Is there a simpler design? Does this change add [unnecessary complexity](/engineering/essays/signals-of-an-over-complex-system/) to the system?\n- What happens when this code fails? Has the failure path been thought through?\n- Does this name carry the right concept? Naming — the part a formatter can't solve, the part that genuinely belongs to a human.\n\nThese can't be automated; that's exactly why they're a human's job.\n\n## A review is a conversation, not a gate\n\nCode review is not gatekeeping. Its purpose isn't only to catch bugs; it's knowledge sharing. The reviewer learns the code, the author gains another perspective, the team converges on a shared standard.\n\nThat's why tone matters: \"why did you do this this way\" should be a real question, not an accusation. A good review culture is one where the author doesn't go on the defensive.\n\n## Small PRs\n\nOne last practical point: big PRs don't get a real review. No one can look deeply at an eight-hundred-line change; the result is an \"LGTM\" and a token approval. Small PRs, on the other hand, actually get read. Keeping the PR small is a precondition for a good review.\n\n---\n\nThe value of a code review is not in the comma it catches but in the design question it asks. Hand everything that can be automated to the tools; leave the human only what a human can answer.\n\nLet the linter look at syntax; you look at architecture.\n\n## Sources\n\n- [What to look for in a code review](https://google.github.io/eng-practices/review/reviewer/looking-for.html) — Google Engineering Practices\n- [Small CLs](https://google.github.io/eng-practices/review/developer/small-cls.html) — Google Engineering Practices",
      "date_published": "2026-11-28T00:00:00.000Z",
      "tags": [
        "code-review",
        "culture",
        "quality",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-prerequisites/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-prerequisites/",
      "title": "Upgrade Prerequisites: A Green Run Is Not Proof",
      "summary": "Choosing the target version does not give you permission to start the upgrade. Before you begin, each of four gates needs a proof you can show: tests running on the target, output that shows any blocking dependency, visible deprecation warnings and a rollback that has actually been run. A gate without proof is the first job of the upgrade.",
      "content_html": "<p>Composer’s <code>platform</code> setting can turn an install green without ever looking at the PHP you will run.</p>\n<p>A green <code>composer install</code> is green against the platform the setting imitates, not against production’s PHP. That is where the gap between choosing a target and being ready to start begins.</p>\n<p><a href=\"https://muhammetsafak.com/engineering/notes/upgrade-target-version/\">Part 4</a> had you write the target as a pair: runtime and framework. For the example system (PHP 8.2 + Laravel 12 + <code>FROM php:8.2-fpm-bookworm</code>) that article’s table came out at 8.4 + Laravel 13; that is the author’s example assumption, not your answer. The target is written. The go is not.</p>\n<p>A go is not a feeling, it is proof you can show. There are four gates, and each is passed with the same two questions: what can you show, and if you cannot, what is the first job?</p>\n<h2 id=\"gate-1-tests-running-on-the-target\">Gate 1: Tests Running on the Target</h2>\n<p>Your test suite may be green on today’s version. That does not say it will be green on the target.</p>\n<p>The proof has two parts. The first is the <strong>baseline</strong>: output showing the suite runs green on the current version, in the current image. If you start from a red baseline, you cannot tell whose fault each red on the target is. The second is the <strong>run on the target</strong>: output of the same suite running in the target image (a tag such as <code>php:8.4-fpm-bookworm</code> in the example), recorded.</p>\n<p>If the suite does not cover the critical path, a green run says nothing. For that path write a <strong>characterization test</strong>: a test that pins down what the code does today, right or wrong, exactly as it is. Its purpose is not to verify behavior but to show whether the output is the same before and after the upgrade. If the output changes on the target, you know the upgrade brought the change.</p>\n<p><strong>If there is no proof, the first job:</strong> get the baseline green, then write characterization tests for the critical paths. These jobs finish before the upgrade, outside it.</p>\n<h2 id=\"gate-2-blocking-dependencies\">Gate 2: Blocking Dependencies</h2>\n<p>If a package in <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">Part 2</a>’s chain blocks the target, the upgrade is stuck before it starts. Ask Composer whether the target fits the chain:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"bash\"><code><span class=\"line\"><span style=\"color:#6F42C1;--shiki-dark:#B392F0\">composer</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> why-not</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> php</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> 8.4</span></span></code></pre>\n<p><code>prohibits</code> (alias <code>why-not</code>) lists which package blocks the requested version. Empty output is good news; but do not trust it alone before checking the trap below.</p>\n<p>The trap is the <code>config.platform</code> setting. It makes Composer imitate a different platform, and Composer’s own documentation says that once it is set, dependencies are no longer checked correctly. A line added to imitate an older PHP keeps the install green if it stays in place in the target image: Composer looks at the imitation, not the real platform.</p>\n<p><code>composer check-platform-reqs</code> ignores this setting and checks the real platform. The <code>--lock</code> flag checks what is in <code>composer.lock</code> instead of the installed packages. Run it inside the target image:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"bash\"><code><span class=\"line\"><span style=\"color:#6F42C1;--shiki-dark:#B392F0\">composer</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> check-platform-reqs</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> --lock</span></span></code></pre>\n<p>No requirement failing, together with <code>config.platform</code> being explained, is the proof. Neither alone.</p>\n<p><strong>If there is no proof, the first job:</strong> review the <code>config.platform</code> line (why is it there, is it still needed), look for a release of the blocking package that supports the target, and if there is none, write down who owns it. The rule Part 4 left applies here: the target cannot go further than the chain’s slowest link.</p>\n<h2 id=\"gate-3-visible-deprecations\">Gate 3: Visible Deprecations</h2>\n<p>Tests can be green and dependencies compatible; the code that runs on the target will still produce deprecation warnings, and if nobody sees them, they have been ignored.</p>\n<p>In Laravel 12, the <code>deprecations</code> log channel is set by the <code>LOG_DEPRECATIONS_CHANNEL</code> environment variable and its <a href=\"https://laravel.com/docs/12.x/logging\">default is <code>null</code></a>: PHP deprecation warnings are produced and thrown away. <code>LOG_DEPRECATIONS_TRACE</code> adds a stack trace showing where the warning came from.</p>\n<p>An example: PHP 8.4 treats a typed parameter whose default is <code>null</code> (<code>string $name = null</code>) as <a href=\"https://www.php.net/manual/en/migration84.deprecated.php\">deprecated</a>; you write <code>?string $name = null</code>. If that pattern exists in your code, running the suite in the target image produces a warning. If the channel is <code>null</code>, no trace is left in the output.</p>\n<p>The proof is running the suite in the target image with the <code>deprecations</code> channel open and writing the output to a file. If the file has no lines, you have proof of visibility; if it has lines, that list is where the upgrade’s job list starts.</p>\n<p>It depends on Gate 1: warnings are produced only for code that runs. If the suite does not exercise the critical path, a clean file only says the code that ran is clean. Split the warnings into your own code and <code>vendor/</code>: the ones in your code you fix, the ones in <code>vendor/</code> go back to Gate 2.</p>\n<p><strong>If there is no proof, the first job:</strong> point the channel at a file, run the suite on the target, and split the output by source.</p>\n<h2 id=\"gate-4-a-way-back\">Gate 4: A Way Back</h2>\n<p>A rollback plan that has not been run once is not a plan, it is an assumption.</p>\n<p>Rollback has three parts: is the previous version’s <strong>artifact</strong> (the image tag) still pullable, is the previous <strong>lock</strong> file at hand, and is there <strong>data</strong> both versions can read. The third is per system. If a serialized record in a queue, a cache or a session was written by the new version, whether the old version can read it stays a question; this article does not answer it, your system does.</p>\n<p>The proof is a rollback run once: bring the new version up on staging, push traffic or a workload through it, then roll back with the previous artifact and lock and show that the system works. “The old image is still there” is not proof; “we went back to the old image and the critical path ran” is.</p>\n<p><strong>If there is no proof, the first job:</strong> run the rollback once on staging. That run shows which data is readable by both versions.</p>\n<h2 id=\"the-proof-table\">The Proof Table</h2>\n<p>Write the four gates on one page:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Gate</th><th>Proof</th><th>If missing, first job</th></tr></thead><tbody><tr><td>1. Tests on the target</td><td>Baseline output + suite output in the target image</td><td>Get the baseline green, write characterization tests</td></tr><tr><td>2. Blocking dependencies</td><td><code>composer why-not</code> and <code>check-platform-reqs --lock</code> output, <code>config.platform</code> explained</td><td>Explain <code>config.platform</code>, write the blocking package’s owner</td></tr><tr><td>3. Visible deprecations</td><td>Suite output on the target, <code>deprecations</code> channel open</td><td>Point the channel at a file, split the output by source</td></tr><tr><td>4. A way back</td><td>Record of a rollback run on staging</td><td>Run the rollback once</td></tr></tbody></table></div>\n<p>A gate without proof does not go away. It gets discovered in the middle of the upgrade, and this time under pressure: inventory, test round and rollback are paid for twice. Collecting the proof up front does that work once.</p>\n<blockquote><p><strong>Tan:</strong> An empty row in the proof table is not a gap, it is information. It tells me what the first job is. In your place I would not try to fill that row; I would leave it empty and write an owner next to it, because keeping the gap visible is cheaper than discovering it during the upgrade.</p></blockquote>\n<h2 id=\"the-limit-of-this-framework\">The Limit of This Framework</h2>\n<p>The table lists the proof needed to start; it does not say starting is enough. Whether a gate’s proof counts as sufficient is per system: what the critical path is, which data both versions can read, how many warnings are acceptable is your system’s answer.</p>\n<p>Rollout order, how much traffic goes to the new version and the doors that cannot be reopened are Part 6’s subject. Here proof is collected; nothing goes to production.</p>\n<p>The detail of commands and settings is in the Composer, Laravel and PHP documentation; read the one for the version you use. The Composer documentation this article leans on is not pinned to a versioned address, so verify your Composer version’s behavior separately.</p>\n<h2 id=\"write-the-four-rows\">Write the Four Rows</h2>\n<p>Back to the green run in the opening: green against which platform?</p>\n<p>Write the four gates on one page for your target version. Attach the proof to the row that has it; the row that does not is the first job of the upgrade.</p>",
      "content_text": "> **TL;DR:** Choosing the target version does not give you permission to start the upgrade. Before you begin, each of four gates needs a proof you can show: tests running on the target, output that shows any blocking dependency, visible deprecation warnings and a rollback that has actually been run. A gate without proof is the first job of the upgrade.\n\nComposer's `platform` setting can turn an install green without ever looking at the PHP you will run.\n\nA green `composer install` is green against the platform the setting imitates, not against production's PHP. That is where the gap between choosing a target and being ready to start begins.\n\n[Part 4](/engineering/notes/upgrade-target-version/) had you write the target as a pair: runtime and framework. For the example system (PHP 8.2 + Laravel 12 + `FROM php:8.2-fpm-bookworm`) that article's table came out at 8.4 + Laravel 13; that is the author's example assumption, not your answer. The target is written. The go is not.\n\nA go is not a feeling, it is proof you can show. There are four gates, and each is passed with the same two questions: what can you show, and if you cannot, what is the first job?\n\n## Gate 1: Tests Running on the Target\n\nYour test suite may be green on today's version. That does not say it will be green on the target.\n\nThe proof has two parts. The first is the **baseline**: output showing the suite runs green on the current version, in the current image. If you start from a red baseline, you cannot tell whose fault each red on the target is. The second is the **run on the target**: output of the same suite running in the target image (a tag such as `php:8.4-fpm-bookworm` in the example), recorded.\n\nIf the suite does not cover the critical path, a green run says nothing. For that path write a **characterization test**: a test that pins down what the code does today, right or wrong, exactly as it is. Its purpose is not to verify behavior but to show whether the output is the same before and after the upgrade. If the output changes on the target, you know the upgrade brought the change.\n\n**If there is no proof, the first job:** get the baseline green, then write characterization tests for the critical paths. These jobs finish before the upgrade, outside it.\n\n## Gate 2: Blocking Dependencies\n\nIf a package in [Part 2](/engineering/notes/upgrade-inventory/)'s chain blocks the target, the upgrade is stuck before it starts. Ask Composer whether the target fits the chain:\n\n```bash\ncomposer why-not php 8.4\n```\n\n`prohibits` (alias `why-not`) lists which package blocks the requested version. Empty output is good news; but do not trust it alone before checking the trap below.\n\nThe trap is the `config.platform` setting. It makes Composer imitate a different platform, and Composer's own documentation says that once it is set, dependencies are no longer checked correctly. A line added to imitate an older PHP keeps the install green if it stays in place in the target image: Composer looks at the imitation, not the real platform.\n\n`composer check-platform-reqs` ignores this setting and checks the real platform. The `--lock` flag checks what is in `composer.lock` instead of the installed packages. Run it inside the target image:\n\n```bash\ncomposer check-platform-reqs --lock\n```\n\nNo requirement failing, together with `config.platform` being explained, is the proof. Neither alone.\n\n**If there is no proof, the first job:** review the `config.platform` line (why is it there, is it still needed), look for a release of the blocking package that supports the target, and if there is none, write down who owns it. The rule Part 4 left applies here: the target cannot go further than the chain's slowest link.\n\n## Gate 3: Visible Deprecations\n\nTests can be green and dependencies compatible; the code that runs on the target will still produce deprecation warnings, and if nobody sees them, they have been ignored.\n\nIn Laravel 12, the `deprecations` log channel is set by the `LOG_DEPRECATIONS_CHANNEL` environment variable and its [default is `null`](https://laravel.com/docs/12.x/logging): PHP deprecation warnings are produced and thrown away. `LOG_DEPRECATIONS_TRACE` adds a stack trace showing where the warning came from.\n\nAn example: PHP 8.4 treats a typed parameter whose default is `null` (`string $name = null`) as [deprecated](https://www.php.net/manual/en/migration84.deprecated.php); you write `?string $name = null`. If that pattern exists in your code, running the suite in the target image produces a warning. If the channel is `null`, no trace is left in the output.\n\nThe proof is running the suite in the target image with the `deprecations` channel open and writing the output to a file. If the file has no lines, you have proof of visibility; if it has lines, that list is where the upgrade's job list starts.\n\nIt depends on Gate 1: warnings are produced only for code that runs. If the suite does not exercise the critical path, a clean file only says the code that ran is clean. Split the warnings into your own code and `vendor/`: the ones in your code you fix, the ones in `vendor/` go back to Gate 2.\n\n**If there is no proof, the first job:** point the channel at a file, run the suite on the target, and split the output by source.\n\n## Gate 4: A Way Back\n\nA rollback plan that has not been run once is not a plan, it is an assumption.\n\nRollback has three parts: is the previous version's **artifact** (the image tag) still pullable, is the previous **lock** file at hand, and is there **data** both versions can read. The third is per system. If a serialized record in a queue, a cache or a session was written by the new version, whether the old version can read it stays a question; this article does not answer it, your system does.\n\nThe proof is a rollback run once: bring the new version up on staging, push traffic or a workload through it, then roll back with the previous artifact and lock and show that the system works. \"The old image is still there\" is not proof; \"we went back to the old image and the critical path ran\" is.\n\n**If there is no proof, the first job:** run the rollback once on staging. That run shows which data is readable by both versions.\n\n## The Proof Table\n\nWrite the four gates on one page:\n\n| Gate | Proof | If missing, first job |\n|---|---|---|\n| 1. Tests on the target | Baseline output + suite output in the target image | Get the baseline green, write characterization tests |\n| 2. Blocking dependencies | `composer why-not` and `check-platform-reqs --lock` output, `config.platform` explained | Explain `config.platform`, write the blocking package's owner |\n| 3. Visible deprecations | Suite output on the target, `deprecations` channel open | Point the channel at a file, split the output by source |\n| 4. A way back | Record of a rollback run on staging | Run the rollback once |\n\nA gate without proof does not go away. It gets discovered in the middle of the upgrade, and this time under pressure: inventory, test round and rollback are paid for twice. Collecting the proof up front does that work once.\n\n\n> **Tan:** An empty row in the proof table is not a gap, it is information. It tells me what the first job is. In your place I would not try to fill that row; I would leave it empty and write an owner next to it, because keeping the gap visible is cheaper than discovering it during the upgrade.\n\n\n## The Limit of This Framework\n\nThe table lists the proof needed to start; it does not say starting is enough. Whether a gate's proof counts as sufficient is per system: what the critical path is, which data both versions can read, how many warnings are acceptable is your system's answer.\n\nRollout order, how much traffic goes to the new version and the doors that cannot be reopened are Part 6's subject. Here proof is collected; nothing goes to production.\n\nThe detail of commands and settings is in the Composer, Laravel and PHP documentation; read the one for the version you use. The Composer documentation this article leans on is not pinned to a versioned address, so verify your Composer version's behavior separately.\n\n## Write the Four Rows\n\nBack to the green run in the opening: green against which platform?\n\nWrite the four gates on one page for your target version. Attach the proof to the row that has it; the row that does not is the first job of the upgrade.\n\n## Sources\n\n- [Command-line interface / Commands](https://getcomposer.org/doc/03-cli.md) — Composer\n- [The composer.json schema / Config](https://getcomposer.org/doc/06-config.md) — Composer\n- [Logging (Laravel 12.x)](https://laravel.com/docs/12.x/logging) — Laravel\n- [Deprecated Features (PHP 8.4)](https://www.php.net/manual/en/migration84.deprecated.php) — PHP",
      "date_published": "2026-11-22T00:00:00.000Z",
      "tags": [
        "testing",
        "dependencies",
        "decisions",
        "production",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/configuration-management/",
      "url": "https://muhammetsafak.com/engineering/notes/configuration-management/",
      "title": "When to Move From .env to Centralized Configuration",
      "summary": "A .env file is enough for one application, a few environments and a small team; moving to a central secret manager is a scale decision made on a measured threshold, not a maturity badge. The signals are a growing number of environments, shared secrets, manual rotation and no audit trail. Regardless of the threshold, separate non-sensitive config from secrets from the start, and keep secrets out of the repository.",
      "content_html": "<p>On one team, <code>.env</code> files were passed hand to hand in Slack DMs. Nobody was sure which secret was current; a rotated key was still sitting in its old form on one server.</p>\n<p><code>.env</code> is the right tool for most projects. The problem is continuing to use it once you’ve outgrown it.</p>\n<h2 id=\"how-far-env-takes-you\">How far .env takes you</h2>\n<p>For a single application, a handful of environments, and a small team, <code>.env</code> is more than enough. It’s simple, everyone knows it, and it needs no extra system. Swapping it out for a secret manager too early adds <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-just-in-case-code/\">complexity for a problem you don’t have</a>.</p>\n<p>Most projects spend their entire life in this simplicity. Before moving on to the next section, make sure you’ve genuinely crossed that threshold.</p>\n<h2 id=\"where-the-cracks-start\">Where the cracks start</h2>\n<p>Concrete signs that <code>.env</code> is no longer enough:</p>\n<ul>\n<li>The number of environments has grown — dev, staging, multiple <a href=\"https://muhammetsafak.com/engineering/systems/laravel-production-stack/\">production environments</a>, preview environments — and the same secret has to be updated by hand in several places.</li>\n<li>Multiple applications share the same secrets; there’s no single source of truth.</li>\n<li>Secret rotation is done manually, and a spot gets missed on a regular basis.</li>\n<li>“Who changed this key, and when?” is a question with no answer.</li>\n<li>A secret is floating around in a chat history or on a developer’s disk.</li>\n</ul>\n<p>Each of these is small on its own; together, they turn secrets into a source of incidents.</p>\n<h2 id=\"what-centralized-configuration-buys-you\">What centralized configuration buys you</h2>\n<p>A secret manager — Vault, AWS Secrets Manager, Doppler, and the like — buys you a single source of truth, automatic rotation, an audit of who accessed what, and access control.</p>\n<p>It has a cost too: one more system to run or depend on, one more tool to learn. That’s why the move is a measured threshold decision, not a fashion.</p>\n<h2 id=\"separate-config-from-secrets\">Separate config from secrets</h2>\n<p>Independent of that threshold, there’s a distinction you should make from the start: <strong>config</strong> and <strong>secret</strong> are not the same thing.</p>\n<ul>\n<li><strong>Config</strong> — non-sensitive settings: feature flags, timeout values, page size. These can comfortably live in the repo, under version control.</li>\n<li><strong>Secret</strong> — values that cause harm when leaked: a database password, an API key, an encryption key. These should never live in the repo.</li>\n</ul>\n<p>Mixing the two into a single <code>.env</code> pile turns even an ordinary settings change into touching a secrets file. Manage the non-sensitive from code; keep the sensitive away from code.</p>\n<h2 id=\"the-migration-threshold\">The migration threshold</h2>\n<p>The decision in one sentence: when secret count × environment count × the number of people touching those secrets turns manual <code>.env</code> management into a measurable source of errors, move to a centralized system. Not because you heard about it at a conference; because you’ve had a real incident from a mishandled secret.</p>\n<p>Unused, forgotten config keys are a separate signal too — as I noted in <a href=\"https://muhammetsafak.com/engineering/essays/signals-of-an-over-complex-system/\">signals of an over-complex system</a>, whichever system you move to, clean out dead settings regularly.</p>\n<hr/>\n<p>Moving from <code>.env</code> to centralized configuration is a scale decision, not a maturity badge. On a small project, a centralized secret manager solves a problem <code>.env</code> doesn’t — that is, nothing.</p>\n<p>Choose the tool for the project’s real size — not the size you dream of.</p>",
      "content_text": "> **TL;DR:** A .env file is enough for one application, a few environments and a small team; moving to a central secret manager is a scale decision made on a measured threshold, not a maturity badge. The signals are a growing number of environments, shared secrets, manual rotation and no audit trail. Regardless of the threshold, separate non-sensitive config from secrets from the start, and keep secrets out of the repository.\n\nOn one team, `.env` files were passed hand to hand in Slack DMs. Nobody was sure which secret was current; a rotated key was still sitting in its old form on one server.\n\n`.env` is the right tool for most projects. The problem is continuing to use it once you've outgrown it.\n\n## How far .env takes you\n\nFor a single application, a handful of environments, and a small team, `.env` is more than enough. It's simple, everyone knows it, and it needs no extra system. Swapping it out for a secret manager too early adds [complexity for a problem you don't have](/engineering/essays/the-cost-of-just-in-case-code/).\n\nMost projects spend their entire life in this simplicity. Before moving on to the next section, make sure you've genuinely crossed that threshold.\n\n## Where the cracks start\n\nConcrete signs that `.env` is no longer enough:\n\n- The number of environments has grown — dev, staging, multiple [production environments](/engineering/systems/laravel-production-stack/), preview environments — and the same secret has to be updated by hand in several places.\n- Multiple applications share the same secrets; there's no single source of truth.\n- Secret rotation is done manually, and a spot gets missed on a regular basis.\n- \"Who changed this key, and when?\" is a question with no answer.\n- A secret is floating around in a chat history or on a developer's disk.\n\nEach of these is small on its own; together, they turn secrets into a source of incidents.\n\n## What centralized configuration buys you\n\nA secret manager — Vault, AWS Secrets Manager, Doppler, and the like — buys you a single source of truth, automatic rotation, an audit of who accessed what, and access control.\n\nIt has a cost too: one more system to run or depend on, one more tool to learn. That's why the move is a measured threshold decision, not a fashion.\n\n## Separate config from secrets\n\nIndependent of that threshold, there's a distinction you should make from the start: **config** and **secret** are not the same thing.\n\n- **Config** — non-sensitive settings: feature flags, timeout values, page size. These can comfortably live in the repo, under version control.\n- **Secret** — values that cause harm when leaked: a database password, an API key, an encryption key. These should never live in the repo.\n\nMixing the two into a single `.env` pile turns even an ordinary settings change into touching a secrets file. Manage the non-sensitive from code; keep the sensitive away from code.\n\n## The migration threshold\n\nThe decision in one sentence: when secret count × environment count × the number of people touching those secrets turns manual `.env` management into a measurable source of errors, move to a centralized system. Not because you heard about it at a conference; because you've had a real incident from a mishandled secret.\n\nUnused, forgotten config keys are a separate signal too — as I noted in [signals of an over-complex system](/engineering/essays/signals-of-an-over-complex-system/), whichever system you move to, clean out dead settings regularly.\n\n---\n\nMoving from `.env` to centralized configuration is a scale decision, not a maturity badge. On a small project, a centralized secret manager solves a problem `.env` doesn't — that is, nothing.\n\nChoose the tool for the project's real size — not the size you dream of.\n\n## Sources\n\n- [Laravel 12.x Configuration: Environment File Security](https://laravel.com/docs/12.x/configuration) — Laravel",
      "date_published": "2026-11-21T00:00:00.000Z",
      "tags": [
        "configuration",
        "infrastructure",
        "production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-target-version/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-target-version/",
      "title": "Upgrade Target Version: Two Dates, Not One",
      "summary": "The upgrade target isn't the newest version: it's the nearest version whose support carries you past the next planned upgrade window and which the dependency chain allows today. The effective horizon is the shorter of the runtime's and the framework's security ends; as long as PHP 8.3 stays on Laravel 12, it hits its ceiling in February 2027. The ceiling is set by the chain's slowest link.",
      "content_html": "<p>PHP 8.3’s security support runs until December 2027; Laravel 12’s ends on 24 February 2027.</p>\n<p>If you won’t upgrade Laravel, the horizon 8.3 gives you is February 2027, not December. When you choose the target, read the two dates and the chain’s slowest link together.</p>\n<p>The matrix in <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-decision-matrix/\">Part 3</a> ranked the system with PHP 8.2 + Laravel 12 + <code>FROM php:8.2-fpm-bookworm</code> first. The order is settled, the version isn’t: 8.3, 8.4 or 8.5?</p>\n<p>There are two easy answers, and both come with a bill. Pick the newest and a link in the chain may not be ready: an extension, a package or the base image doesn’t support that version yet. Pick the nearest and on the day you finish the upgrade you’ve also written the calendar for the next one; a year later you’re back at the top of the same table.</p>\n<p>The example system stays the same: the PHP 8.2 system the matrix ranked first. The method runs once per system.</p>\n<h2 id=\"the-first-date-does-it-outlast-the-window\">The First Date: Does It Outlast the Window</h2>\n<p>The first of the two dates is the candidate’s own security end date, and it doesn’t decide alone: it means something only when you set it next to the system’s next planned upgrade window.</p>\n<p><strong>The next planned window</strong> is the first date by which you could finish another upgrade after finishing this one. If the team’s upgrade rhythm is yearly, it’s 12 months after the day this upgrade ends. If your rhythm is different, write your own; the method doesn’t change, only the date shifts.</p>\n<p>The rule: if the candidate’s security end doesn’t reach beyond that window, the second upgrade is already on the calendar. <a href=\"https://www.php.net/supported-versions.php\">php.net</a> gives these dates for the four candidates:</p>\n<ul>\n<li><strong>PHP 8.2:</strong> 31 December 2026</li>\n<li><strong>PHP 8.3:</strong> 31 December 2027</li>\n<li><strong>PHP 8.4:</strong> 31 December 2028</li>\n<li><strong>PHP 8.5:</strong> 31 December 2029</li>\n</ul>\n<p>All four dates are the last day of the year; there are exactly 12 months between them. So the question comes down to a plain comparison: is the window date before the candidate’s security end, or after?</p>\n<p>PHP 8.6 isn’t on this list. <a href=\"https://wiki.php.net/todo/php86\">wiki.php.net</a> gives its GA date as 19 November 2026; that is, it comes out four days after this post’s publication day. On top of that, neither Laravel 12 nor Laravel 13 supports 8.6 (in the second-date section). It isn’t a candidate today.</p>\n<p>The cost of a “safe short step” that doesn’t reach the window shows up here too. If you move to 8.3 and your rhythm is yearly, the second upgrade is on the calendar the day you finish the first. The second isn’t half the work of the first: you rebuild the inventory, rerun the test round, replan the rollout. The inventory and the test round get paid for twice.</p>\n<p>A short step doesn’t have to be a wrong choice. What’s wrong is choosing it because it’s “cheap” and not writing down the second bill. If you did write it down, that is, if you put the second upgrade on the calendar together with its budget, 8.3 is a defensible target.</p>\n<h2 id=\"the-second-date-the-frameworks-horizon\">The Second Date: The Framework’s Horizon</h2>\n<p>The runtime’s horizon can’t be longer than the horizon of the framework above it. As long as the system stays on Laravel 12, the effective date is the shorter of the two.</p>\n<p><a href=\"https://laravel.com/docs/12.x/releases\">Laravel 12</a> supports PHP 8.2–8.5 and ships security fixes until 24 February 2027. <a href=\"https://laravel.com/docs/13.x/releases\">Laravel 13</a> supports PHP 8.3–8.5 and its security fixes continue until 17 March 2028. 8.6 isn’t in the range either version supports.</p>\n<p>Back to the opening example: 8.3 + Laravel 12. The PHP side runs to December 2027, the framework side to February 2027. The effective horizon is February 2027; that is, this combination hits its own ceiling just 55 days after 8.2’s end on 31 December 2026.</p>\n<p>There are two ways out:</p>\n<ol>\n<li><strong>Make the framework upgrade part of the target.</strong> With 8.3 + Laravel 13 the horizon extends to March 2028. But this work gets added next to the runtime upgrade as a second job; the scope grows.</li>\n<li><strong>Write the horizon as February 2027.</strong> If you’ve decided not to upgrade the framework, that is the target’s real horizon. Recording it openly is cheaper than being surprised later.</li>\n</ol>\n<p>There’s no hidden option: either the framework enters the target or the horizon shortens. If you chose the second, write the shorter of the two dates in your table’s “security end” column, not PHP’s; otherwise the table shows a horizon longer than it really is, from the first row on. A single “PHP 8.3” row squeezes the two into the same date.</p>\n<h2 id=\"the-slowest-link-sets-the-target\">The Slowest Link Sets the Target</h2>\n<p>The counter-intuitive part: the newest version gives the longest support, but it doesn’t set the target. The chain’s slowest link does.</p>\n<p>The chain in <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">Part 2</a> ran from the bottom up: runtime, extensions, framework, packages, container image, CI. The candidate version has to work at every link. If one link doesn’t support the candidate, the candidate is out; it doesn’t matter how long its support is.</p>\n<p>So the check runs in reverse:</p>\n<ul>\n<li>Does every extension have a release for the candidate version?</li>\n<li>Does the <code>php</code> constraint of the packages in <code>composer.json</code> cover the candidate? <code>composer check-platform-reqs</code> reads this for you when run with the candidate PHP (for example inside the candidate image).</li>\n<li>Is the base image tag published for the candidate version? In the example system, instead of <code>php:8.2-fpm-bookworm</code> you need a tag like <code>php:8.4-fpm-bookworm</code>.</li>\n<li>Can the CI matrix run the candidate version?</li>\n</ul>\n<p>The slowest link is the first row in the list that stops the candidate; it sets the order, not you. If several links stop it, the one furthest behind sets the ceiling.</p>\n<p>The newest version the chain allows is the target’s upper bound. Downward, the two dates do the limiting: a candidate that doesn’t reach far enough is out.</p>\n<p>Before you pick 8.4, look at your extension list: if one isn’t ready, your target is 8.3, not 8.4. A link that isn’t ready is a blocker, but it’s also a date: the day that link moves to 8.4 is the day the target can shift to 8.4. If you own the link (a package you wrote, an extension you compile yourself), you set the date; if not, there’s nothing to do but watch it.</p>\n<h2 id=\"target-selection-table\">Target Selection Table</h2>\n<p>One row per candidate; the two dates and the chain get a column each:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Candidate</th><th>Security end</th><th>Next window</th><th>Chain allows</th><th>Decision</th></tr></thead><tbody><tr><td>8.3</td><td>31 December 2027</td><td>End of December 2027</td><td>Yes</td><td>Doesn’t outlast the window, out</td></tr><tr><td>8.4</td><td>31 December 2028</td><td>End of December 2027</td><td>Yes</td><td>Target</td></tr><tr><td>8.5</td><td>31 December 2029</td><td>End of December 2027</td><td>No</td><td>Chain blocks it, out</td></tr></tbody></table></div>\n<p>The security end column is from <a href=\"https://www.php.net/supported-versions.php\">php.net</a>. <strong>The window and chain columns are my example assumption</strong>, not a case: I assumed the upgrade ends at the end of 2026, the rhythm is yearly, the framework is upgraded to Laravel 13, and the slowest link (in the example, an extension) doesn’t support 8.5 yet. Your rows fill with your own dates.</p>\n<p>Under those assumptions the table says: 8.3’s PHP horizon lands on the same day as the window, with no margin; with Laravel 12 the horizon drops to February 2027. 8.5 is the best on horizon, but the chain doesn’t allow it. That leaves 8.4: together with Laravel 13 its horizon reaches March 2028, it outlasts the window and the chain allows it.</p>\n<p>The rule fits in one sentence: <strong>the nearest version that outlasts the window and that the chain allows.</strong></p>\n<p>“Nearest” matters. If several candidates pass both conditions, pick the smaller one: a version further ahead brings along links the chain hasn’t prepared yet. As the chain matures, that version becomes a candidate again in the next window, with its own dates.</p>\n<blockquote><p><strong>Tan:</strong> Write only the PHP version on the target line and half of the decision stays invisible. In the example, 8.4 only means something together with the move to Laravel 13; if the framework stays where it is, the same line shows a shorter horizon. So I write the target as a pair, runtime and framework on the same line. Whoever reads that line then sees the second job as part of the plan too.</p></blockquote>\n<h2 id=\"the-limit-of-this-framework\">The Limit of This Framework</h2>\n<p>The table gives the target. It doesn’t tell you whether you’re ready: your tests, your way back and your prerequisites are in Part 5.</p>\n<p>The target coming out as 8.4 doesn’t mean you can start today. The chain saying “allows” doesn’t mean that link has been tested with the candidate; it means only that it supports it.</p>\n<p>The table isn’t a one-off either. If the window shifts, a link gets ready earlier than expected, or the framework’s calendar changes, the rows are read again; the target is written once, but retested against the dates in every planning round.</p>\n<p>The dates are the calendar php.net publishes. What happens after a version’s support ends depends on your source: if you install PHP from your distribution’s package, the distribution may backport its own security fixes; its calendar can differ from php.net’s. Saying “no fix will ever come” once you pass the date would be wrong, but saying “I can count on a fix” is also a decision, and it should go on the record.</p>\n<h2 id=\"write-the-target-on-one-line\">Write the Target on One Line</h2>\n<p>Back to the opening question: is 8.3’s horizon December or February? February, as long as you stay on Laravel 12. December only if the framework enters the target too; even then the target doesn’t have to be 8.3.</p>\n<p>Two dates and a link don’t leave “which version?” to guesswork. <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-decision-matrix/\">Part 3</a> gave the order, this post the version, and the inventory in <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">Part 2</a> the input for both.</p>\n<p>For the system the matrix ranked first, write the candidate versions into the table, compare their security ends with your next window and your chain’s slowest link, and note the target as a single line.</p>",
      "content_text": "> **TL;DR:** The upgrade target isn't the newest version: it's the nearest version whose support carries you past the next planned upgrade window and which the dependency chain allows today. The effective horizon is the shorter of the runtime's and the framework's security ends; as long as PHP 8.3 stays on Laravel 12, it hits its ceiling in February 2027. The ceiling is set by the chain's slowest link.\n\nPHP 8.3's security support runs until December 2027; Laravel 12's ends on 24 February 2027.\n\nIf you won't upgrade Laravel, the horizon 8.3 gives you is February 2027, not December. When you choose the target, read the two dates and the chain's slowest link together.\n\nThe matrix in [Part 3](/engineering/notes/upgrade-decision-matrix/) ranked the system with PHP 8.2 + Laravel 12 + `FROM php:8.2-fpm-bookworm` first. The order is settled, the version isn't: 8.3, 8.4 or 8.5?\n\nThere are two easy answers, and both come with a bill. Pick the newest and a link in the chain may not be ready: an extension, a package or the base image doesn't support that version yet. Pick the nearest and on the day you finish the upgrade you've also written the calendar for the next one; a year later you're back at the top of the same table.\n\nThe example system stays the same: the PHP 8.2 system the matrix ranked first. The method runs once per system.\n\n## The First Date: Does It Outlast the Window\n\nThe first of the two dates is the candidate's own security end date, and it doesn't decide alone: it means something only when you set it next to the system's next planned upgrade window.\n\n**The next planned window** is the first date by which you could finish another upgrade after finishing this one. If the team's upgrade rhythm is yearly, it's 12 months after the day this upgrade ends. If your rhythm is different, write your own; the method doesn't change, only the date shifts.\n\nThe rule: if the candidate's security end doesn't reach beyond that window, the second upgrade is already on the calendar. [php.net](https://www.php.net/supported-versions.php) gives these dates for the four candidates:\n\n- **PHP 8.2:** 31 December 2026\n- **PHP 8.3:** 31 December 2027\n- **PHP 8.4:** 31 December 2028\n- **PHP 8.5:** 31 December 2029\n\nAll four dates are the last day of the year; there are exactly 12 months between them. So the question comes down to a plain comparison: is the window date before the candidate's security end, or after?\n\nPHP 8.6 isn't on this list. [wiki.php.net](https://wiki.php.net/todo/php86) gives its GA date as 19 November 2026; that is, it comes out four days after this post's publication day. On top of that, neither Laravel 12 nor Laravel 13 supports 8.6 (in the second-date section). It isn't a candidate today.\n\nThe cost of a \"safe short step\" that doesn't reach the window shows up here too. If you move to 8.3 and your rhythm is yearly, the second upgrade is on the calendar the day you finish the first. The second isn't half the work of the first: you rebuild the inventory, rerun the test round, replan the rollout. The inventory and the test round get paid for twice.\n\nA short step doesn't have to be a wrong choice. What's wrong is choosing it because it's \"cheap\" and not writing down the second bill. If you did write it down, that is, if you put the second upgrade on the calendar together with its budget, 8.3 is a defensible target.\n\n## The Second Date: The Framework's Horizon\n\nThe runtime's horizon can't be longer than the horizon of the framework above it. As long as the system stays on Laravel 12, the effective date is the shorter of the two.\n\n[Laravel 12](https://laravel.com/docs/12.x/releases) supports PHP 8.2–8.5 and ships security fixes until 24 February 2027. [Laravel 13](https://laravel.com/docs/13.x/releases) supports PHP 8.3–8.5 and its security fixes continue until 17 March 2028. 8.6 isn't in the range either version supports.\n\nBack to the opening example: 8.3 + Laravel 12. The PHP side runs to December 2027, the framework side to February 2027. The effective horizon is February 2027; that is, this combination hits its own ceiling just 55 days after 8.2's end on 31 December 2026.\n\nThere are two ways out:\n\n1. **Make the framework upgrade part of the target.** With 8.3 + Laravel 13 the horizon extends to March 2028. But this work gets added next to the runtime upgrade as a second job; the scope grows.\n2. **Write the horizon as February 2027.** If you've decided not to upgrade the framework, that is the target's real horizon. Recording it openly is cheaper than being surprised later.\n\nThere's no hidden option: either the framework enters the target or the horizon shortens. If you chose the second, write the shorter of the two dates in your table's \"security end\" column, not PHP's; otherwise the table shows a horizon longer than it really is, from the first row on. A single \"PHP 8.3\" row squeezes the two into the same date.\n\n## The Slowest Link Sets the Target\n\nThe counter-intuitive part: the newest version gives the longest support, but it doesn't set the target. The chain's slowest link does.\n\nThe chain in [Part 2](/engineering/notes/upgrade-inventory/) ran from the bottom up: runtime, extensions, framework, packages, container image, CI. The candidate version has to work at every link. If one link doesn't support the candidate, the candidate is out; it doesn't matter how long its support is.\n\nSo the check runs in reverse:\n\n- Does every extension have a release for the candidate version?\n- Does the `php` constraint of the packages in `composer.json` cover the candidate? `composer check-platform-reqs` reads this for you when run with the candidate PHP (for example inside the candidate image).\n- Is the base image tag published for the candidate version? In the example system, instead of `php:8.2-fpm-bookworm` you need a tag like `php:8.4-fpm-bookworm`.\n- Can the CI matrix run the candidate version?\n\nThe slowest link is the first row in the list that stops the candidate; it sets the order, not you. If several links stop it, the one furthest behind sets the ceiling.\n\nThe newest version the chain allows is the target's upper bound. Downward, the two dates do the limiting: a candidate that doesn't reach far enough is out.\n\nBefore you pick 8.4, look at your extension list: if one isn't ready, your target is 8.3, not 8.4. A link that isn't ready is a blocker, but it's also a date: the day that link moves to 8.4 is the day the target can shift to 8.4. If you own the link (a package you wrote, an extension you compile yourself), you set the date; if not, there's nothing to do but watch it.\n\n## Target Selection Table\n\nOne row per candidate; the two dates and the chain get a column each:\n\n| Candidate | Security end | Next window | Chain allows | Decision |\n|---|---|---|---|---|\n| 8.3 | 31 December 2027 | End of December 2027 | Yes | Doesn't outlast the window, out |\n| 8.4 | 31 December 2028 | End of December 2027 | Yes | Target |\n| 8.5 | 31 December 2029 | End of December 2027 | No | Chain blocks it, out |\n\nThe security end column is from [php.net](https://www.php.net/supported-versions.php). **The window and chain columns are my example assumption**, not a case: I assumed the upgrade ends at the end of 2026, the rhythm is yearly, the framework is upgraded to Laravel 13, and the slowest link (in the example, an extension) doesn't support 8.5 yet. Your rows fill with your own dates.\n\nUnder those assumptions the table says: 8.3's PHP horizon lands on the same day as the window, with no margin; with Laravel 12 the horizon drops to February 2027. 8.5 is the best on horizon, but the chain doesn't allow it. That leaves 8.4: together with Laravel 13 its horizon reaches March 2028, it outlasts the window and the chain allows it.\n\nThe rule fits in one sentence: **the nearest version that outlasts the window and that the chain allows.**\n\n\"Nearest\" matters. If several candidates pass both conditions, pick the smaller one: a version further ahead brings along links the chain hasn't prepared yet. As the chain matures, that version becomes a candidate again in the next window, with its own dates.\n\n\n> **Tan:** Write only the PHP version on the target line and half of the decision stays invisible. In the example, 8.4 only means something together with the move to Laravel 13; if the framework stays where it is, the same line shows a shorter horizon. So I write the target as a pair, runtime and framework on the same line. Whoever reads that line then sees the second job as part of the plan too.\n\n\n## The Limit of This Framework\n\nThe table gives the target. It doesn't tell you whether you're ready: your tests, your way back and your prerequisites are in Part 5.\n\nThe target coming out as 8.4 doesn't mean you can start today. The chain saying \"allows\" doesn't mean that link has been tested with the candidate; it means only that it supports it.\n\nThe table isn't a one-off either. If the window shifts, a link gets ready earlier than expected, or the framework's calendar changes, the rows are read again; the target is written once, but retested against the dates in every planning round.\n\nThe dates are the calendar php.net publishes. What happens after a version's support ends depends on your source: if you install PHP from your distribution's package, the distribution may backport its own security fixes; its calendar can differ from php.net's. Saying \"no fix will ever come\" once you pass the date would be wrong, but saying \"I can count on a fix\" is also a decision, and it should go on the record.\n\n## Write the Target on One Line\n\nBack to the opening question: is 8.3's horizon December or February? February, as long as you stay on Laravel 12. December only if the framework enters the target too; even then the target doesn't have to be 8.3.\n\nTwo dates and a link don't leave \"which version?\" to guesswork. [Part 3](/engineering/notes/upgrade-decision-matrix/) gave the order, this post the version, and the inventory in [Part 2](/engineering/notes/upgrade-inventory/) the input for both.\n\nFor the system the matrix ranked first, write the candidate versions into the table, compare their security ends with your next window and your chain's slowest link, and note the target as a single line.\n\n## Sources\n\n- [Supported Versions](https://www.php.net/supported-versions.php) — PHP\n- [Laravel 12.x Release Notes](https://laravel.com/docs/12.x/releases) — Laravel\n- [Laravel 13.x Release Notes](https://laravel.com/docs/13.x/releases) — Laravel\n- [todo:php86](https://wiki.php.net/todo/php86) — PHP",
      "date_published": "2026-11-15T00:00:00.000Z",
      "tags": [
        "dependencies",
        "decisions",
        "security",
        "production",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/global-state-management/",
      "url": "https://muhammetsafak.com/engineering/notes/global-state-management/",
      "title": "The Invisible Side Effects of Global State",
      "summary": "Global state creates a dependency that the function signature does not show: a value changed in one place is read in another unrelated one, state leaks between tests and the bug is found only while debugging. The danger grows in long-running processes such as queue workers and Octane. The fix is not to eliminate state but to make it visible and local through parameters, dependency injection and request or job scope.",
      "content_html": "<p>There was a bug where a value changed “on its own.” The test passed when run alone, but failed when run with the whole suite. One request behaved differently depending on the request that came before it. The culprit was shared, mutable global state.</p>\n<p>Global state shortens the code — and lengthens the debugging.</p>\n<h2 id=\"what-global-means\">What “global” means</h2>\n<p>“Global” here is more than the <code>global</code> keyword. Static properties carrying mutable state, stateful singletons, module-level mutable variables, shared state hidden behind a framework facade — all belong to the same category.</p>\n<p>The common trait: a value changed in one place can be read in another, unrelated place.</p>\n<h2 id=\"the-invisible-coupling\">The invisible coupling</h2>\n<p>The real cost of global state is the <strong>invisible coupling</strong> it creates. A function’s signature tells you what it needs — its parameters. But if the function reads and mutates a global, the signature lies. The function depends on something its signature never shows.</p>\n<p>This is called “action at a distance”: a change in one file alters the behavior of another file that has no visible connection to it. You can’t see this coupling by reading the code; you discover it only while debugging.</p>\n<h2 id=\"untestability\">Untestability</h2>\n<p>The <a href=\"https://muhammetsafak.com/engineering/essays/signals-of-an-over-complex-system/\">earliest signal</a> of global state shows up in the tests. State leaks between tests: one test sets a global, the next test finds it already set. Tests become order-dependent — they pass alone and fail together.</p>\n<p>The workaround is to reset the globals before every test. That very need to reset is the smell itself: the code confesses, through its test setup, that it depends on shared state.</p>\n<h2 id=\"the-danger-in-long-running-processes\">The danger in long-running processes</h2>\n<p>In PHP’s classic request-response model, global state resets on every request; the danger is partly hidden. But in a long-lived process — in a <a href=\"https://muhammetsafak.com/engineering/notes/laravel-queue-production-slowdown/\">queue worker</a> — it’s a different story.</p>\n<p>The worker stays alive between jobs. A value written to a global by job 1 leaks into job 2. A bug invisible when you test locally with a single job, exploding in production when thousands of jobs run back to back. Persistent application servers like Octane bring the same risk to classic web requests too.</p>\n<h2 id=\"localizing-state\">Localizing state</h2>\n<p>The solution isn’t to eliminate state — every system has state — it’s to make it <strong>visible and local</strong>:</p>\n<ul>\n<li>Instead of reading state from a global, pass it as a parameter. An explicit dependency, visible in the signature.</li>\n<li>Supply dependencies through dependency injection, not hidden access.</li>\n<li>Keep mutable state scoped to the request or job, not the process. Let a job’s state begin and end with that job.</li>\n</ul>\n<p>The rule is plain: explicit beats implicit. If everything a function needs is visible in its signature, that function is both readable and testable.</p>\n<hr/>\n<p>Global state is tempting because it saves you from writing a few parameters. In return, it makes you hunt for hours to find where a value changed.</p>\n<p>Every global is a hidden coupling left in the code — turn it into a parameter.</p>",
      "content_text": "> **TL;DR:** Global state creates a dependency that the function signature does not show: a value changed in one place is read in another unrelated one, state leaks between tests and the bug is found only while debugging. The danger grows in long-running processes such as queue workers and Octane. The fix is not to eliminate state but to make it visible and local through parameters, dependency injection and request or job scope.\n\nThere was a bug where a value changed \"on its own.\" The test passed when run alone, but failed when run with the whole suite. One request behaved differently depending on the request that came before it. The culprit was shared, mutable global state.\n\nGlobal state shortens the code — and lengthens the debugging.\n\n## What \"global\" means\n\n\"Global\" here is more than the `global` keyword. Static properties carrying mutable state, stateful singletons, module-level mutable variables, shared state hidden behind a framework facade — all belong to the same category.\n\nThe common trait: a value changed in one place can be read in another, unrelated place.\n\n## The invisible coupling\n\nThe real cost of global state is the **invisible coupling** it creates. A function's signature tells you what it needs — its parameters. But if the function reads and mutates a global, the signature lies. The function depends on something its signature never shows.\n\nThis is called \"action at a distance\": a change in one file alters the behavior of another file that has no visible connection to it. You can't see this coupling by reading the code; you discover it only while debugging.\n\n## Untestability\n\nThe [earliest signal](/engineering/essays/signals-of-an-over-complex-system/) of global state shows up in the tests. State leaks between tests: one test sets a global, the next test finds it already set. Tests become order-dependent — they pass alone and fail together.\n\nThe workaround is to reset the globals before every test. That very need to reset is the smell itself: the code confesses, through its test setup, that it depends on shared state.\n\n## The danger in long-running processes\n\nIn PHP's classic request-response model, global state resets on every request; the danger is partly hidden. But in a long-lived process — in a [queue worker](/engineering/notes/laravel-queue-production-slowdown/) — it's a different story.\n\nThe worker stays alive between jobs. A value written to a global by job 1 leaks into job 2. A bug invisible when you test locally with a single job, exploding in production when thousands of jobs run back to back. Persistent application servers like Octane bring the same risk to classic web requests too.\n\n## Localizing state\n\nThe solution isn't to eliminate state — every system has state — it's to make it **visible and local**:\n\n- Instead of reading state from a global, pass it as a parameter. An explicit dependency, visible in the signature.\n- Supply dependencies through dependency injection, not hidden access.\n- Keep mutable state scoped to the request or job, not the process. Let a job's state begin and end with that job.\n\nThe rule is plain: explicit beats implicit. If everything a function needs is visible in its signature, that function is both readable and testable.\n\n---\n\nGlobal state is tempting because it saves you from writing a few parameters. In return, it makes you hunt for hours to find where a value changed.\n\nEvery global is a hidden coupling left in the code — turn it into a parameter.\n\n## Sources\n\n- [Laravel 12.x Octane: Dependency Injection and Octane](https://laravel.com/docs/12.x/octane#dependency-injection-and-octane) — Laravel",
      "date_published": "2026-11-14T00:00:00.000Z",
      "tags": [
        "architecture",
        "state",
        "quality"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-decision-matrix/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-decision-matrix/",
      "title": "Upgrade Decision Matrix: Criticality and Type, Not Date",
      "summary": "The upgrade order is set not by the end-of-support date but by the system's criticality together with the trigger's type (mandatory, locking, opportunity); the same CVE is an opportunity in an internal tool and mandatory in a payment flow. A 3×3 matrix gives each cell a rank and a response window, and the EOL date is only the ceiling. Because the type drifts over time, the matrix is re-read in every planning round.",
      "content_html": "<p>An upgrade queue sorted by date can push the mandatory signal of your most critical system to the bottom.</p>\n<p>Picture a queue like this. You have an inventory and you have an EOL list; you merge them and sort by date. At the top sits the row whose EOL is nearest: an internal reporting tool used only by the team. At the bottom sits the row with no date, or the most distant one: a CVE that affects you in the payment flow.</p>\n<p>The sorting worked correctly. What was wrong was what it sorted.</p>\n<p><a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">Part 2</a> drew the line from the start: the inventory doesn’t make decisions, it produces input for the decision matrix. The date is one column of that input, nothing more. Without knowing what a system stops when it goes down, and what type of signal you are holding, a date can’t put the queue in order.</p>\n<p>The date is only an upper bound; the order is set by the system’s criticality and the trigger’s type together.</p>\n<h2 id=\"the-same-cve-two-different-cells\">The Same CVE, Two Different Cells</h2>\n<p>Suppose two systems use the same package, and a CVE is published for one component of that package. The two questions from <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-triggers/\">Part 1</a> are the tiebreaker here: am I using the affected component, and can the affected code path be reached from outside?</p>\n<ul>\n<li><strong>Internal reporting tool.</strong> The component is there too, but only the team reaches the tool, and only from the company network. The second answer is “no”. The signal is an opportunity; a “not affected” record is filed.</li>\n<li><strong>Payment flow.</strong> The same component sits behind an endpoint reachable from the internet. Both answers are “yes”. The signal is mandatory.</li>\n</ul>\n<p>Same package, same CVE, same severity score. Different order. Severity measures how bad the component is; it doesn’t measure what your system would lose if it went down. That’s why severity alone doesn’t set the order.</p>\n<p>Type is a property of signal × system: criticality labels the system, and type is the value the signal takes on when it lands on that system. The matrix crosses the two.</p>\n<p>The “opportunity” label on the internal tool isn’t a permanent verdict either. If the tool is opened to the internet tomorrow, or an exploit is published before a fix arrives, both answers become “yes” and the signal moves to mandatory. That’s why the record should carry the reasoning, not the result: the sentence “can’t be reached from outside” also tells you under what condition to look again.</p>\n<h2 id=\"three-classes-three-types-nine-cells\">Three Classes, Three Types, Nine Cells</h2>\n<p>First the axes. Criticality is defined by what the system stops when it goes down. I use three classes:</p>\n<ul>\n<li><strong>Critical:</strong> stops revenue or the customer flow (payment, login, orders).</li>\n<li><strong>Medium:</strong> stops the work of a team or a customer segment, while the main flow continues (admin panel, reporting, integration).</li>\n<li><strong>Low:</strong> nobody notices for days when it stops (internal tool, one-off batch).</li>\n</ul>\n<p>The type axis is familiar from Part 1: mandatory, locking, opportunity. The order comes out in two steps: type first, then criticality within the type. The windows in the cells are my recommendation, not an industry standard. Shift them to your team’s capacity, but write a window down.</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th></th><th>Mandatory</th><th>Locking</th><th>Opportunity</th></tr></thead><tbody><tr><td><strong>Critical</strong></td><td><strong>1</strong> · triage the same business day, patch within 7 days; on EOL, at least 3 months before the end date</td><td><strong>4</strong> · into this quarter’s plan</td><td><strong>7</strong> · into the quarter’s plan if there is a measured gain</td></tr><tr><td><strong>Medium</strong></td><td><strong>2</strong> · triage within 1 business day, patch within 14 days; on EOL, at least 2 months before the end date</td><td><strong>5</strong> · into next quarter’s plan</td><td><strong>8</strong> · backlog</td></tr><tr><td><strong>Low</strong></td><td><strong>3</strong> · triage within 1 week, patch within 30 days; on EOL, at least 1 month before the end date, or shut the system down</td><td><strong>6</strong> · before the next major</td><td><strong>9</strong> · no date</td></tr></tbody></table></div>\n<p>Placing a signal in a cell takes three steps: determine the system’s class, take the signal’s type from the table in Part 1, and read the rank and window at the intersection. If several signals land in the same cell, the one with the nearer EOL date goes first. Between cells, the date doesn’t set the order; it can only narrow the window.</p>\n<p>I won’t walk through all nine cells one by one; two corners are enough.</p>\n<p>Critical × mandatory is rank one: the most expensive system when it goes down, and a signal that can’t be made to wait. This is exactly where the row that sank to the bottom of the opening queue belongs. The date column couldn’t give it a rank, because a CVE doesn’t fit a calendar.</p>\n<p>Low × opportunity is rank nine. That doesn’t mean “never do it”, it means “don’t give it a date”: it gets done when you’re already in that repo for some other job. The function of rank nine is to keep this work from swelling the queue and slowing down the rank-one job.</p>\n<p>The middle cells sit between the two corners, and this is where most of the arguments start: Medium × mandatory versus Critical × locking. My recommendation is to put the mandatory one first. A mandatory signal’s date or exploitation risk moves independently of you; a lock may break nothing today, but it has a budget on a quarterly scale. If the lock’s budget is about to run out, breaking this rule is a decision that belongs to you, and the matrix doesn’t forbid it.</p>\n<p>If a window and an EOL collide, the EOL wins. The duration in the cell is the rule itself, the EOL date is the ceiling; whichever comes earlier applies. The 30 days of the Low × mandatory cell drops to 20 days if 20 days remain until the end date.</p>\n<p>EOL also has a gap between “upstream is finished” and “no fix will come”. Debian 12’s EOL date is <a href=\"https://wiki.debian.org/DebianReleases\">12 July 2026</a>; according to the same page, LTS continues until 30 June 2028. If you rely on LTS or on another extended support (ELS) provider, your ceiling is that date. But reading which packages are covered, and writing the note “relies on LTS” into the cell, is your job.</p>\n<h2 id=\"cells-dont-stay-put\">Cells Don’t Stay Put</h2>\n<p>The matrix is a photograph; signals move. Type drifts over time: an opportunity turns into a locking one, a locking one into a mandatory one. The mechanism is simple: a deferred opportunity narrows the options, and a narrowing option runs into a date.</p>\n<p>Picture a medium-criticality system running on PHP 8.2. When a new major version of a package you use comes out, moving to it is an opportunity; the old major still works, nothing breaks. When the package stops shipping fixes to the old major, the same job turns into a locking one. If a security fix arrives only in the new major, the lock turns into a mandatory one.</p>\n<p>The runtime row doesn’t walk this path, because on the day the EOL date is published the signal is already mandatory. <a href=\"https://www.php.net/supported-versions.php\">php.net</a> says 8.2’s security support ends on <strong>31 December 2026</strong>; that is 53 days after this post’s publication date. The Medium × mandatory cell wants the work finished at least 2 months before the end date; that window closed before this post was published.</p>\n<p>Two clocks run at once in the same system. The <a href=\"https://laravel.com/docs/12.x/releases\">Laravel 12.x release notes</a> say Laravel 12’s security fixes continue until <strong>24 February 2027</strong>. The runtime row and the framework row hit their ceilings 55 days apart. A single “PHP 8.2” row squeezes these two ceilings into one date.</p>\n<p>The second axis drifts too, but for a different reason: criticality changes not with time but with the work. An internal tool that opens an endpoint into the payment flow moves from Low to Critical that day. The code stays the same, its class changes.</p>\n<p>The direction of drift is one-way: an opportunity walks toward mandatory on its own and doesn’t come back. So a “we’ll look at it later” decision isn’t free; every round moves the cell one step closer to mandatory. A deferred job doesn’t stay cheap, it moves toward an expensive date.</p>\n<p>That’s why you shouldn’t fill in the matrix once and bury it in the queue. In every planning round, re-read each signal’s cell. Keep the cell next to the signal (an issue label, a PR description); then drift isn’t a surprise, it’s the first item of the round.</p>\n<blockquote><p><strong>Tan:</strong> Write down every decision that breaks the matrix's rule, with its reason and an end date. A job moved up because of a dependency lock should go back to its own cell once the lock is lifted. An exception nobody wrote down will be read as the rule in the next planning round.</p></blockquote>\n<h2 id=\"the-limit-of-this-framework\">The Limit of This Framework</h2>\n<p>The matrix gives the order. It doesn’t give the target version: whether it’s 8.3, 8.4 or 8.5 is decided in Part 4. It doesn’t tell you whether you’re ready either: your tests, your way back and your dependency map are in Part 5.</p>\n<p>Being first in line doesn’t mean being ready to start. The matrix says “this first”; it doesn’t say “this today”. If the system at rank one has no tests, the first job may not be the upgrade but writing those tests; Part 5 will draw that distinction.</p>\n<p>The matrix also doesn’t tell you, in your place, which class a system falls into. “Is this system Critical or Medium?” is the first argument in most teams. If you keep the definition question as “what stops when it goes down?”, the argument gets shorter: the answer should point to a workflow, not to a product feature.</p>\n<p>The three classes are deliberately coarse. There is no risk score or formula here; a team that needs a formula can split the classes into four, and the logic of the matrix doesn’t change.</p>\n<h2 id=\"reorder-the-queue\">Reorder the Queue</h2>\n<p>Back to the start. The internal reporting tool was at the top, the CVE in the payment flow at the bottom. With the matrix the order flips: payment × mandatory comes first, and the internal tool, even though its EOL is near, drops to third, into its own window. The date didn’t take the internal tool out of the queue; it only gave up deciding its position.</p>\n<p>A queue that moves in date order makes the work look calm: every row has a day, none of them is wrong. The matrix breaks that calm, because it pulls some rows forward without looking at their date. It’s uncomfortable, but it’s correct.</p>\n<p>The cost of getting the order wrong is written in <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/\">Part 0</a>. <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-triggers/\">Part 1</a> sorted the signals into types, and <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">Part 2</a> sorted the system into layers. This part turned the two into an order.</p>\n<p>A date can be a reason to enter the queue; it isn’t enough to set the order.</p>\n<p>Sort the systems in your inventory into three criticality classes, place the upgrade signals in your queue into the matrix, and take the one in the top cell into this sprint.</p>",
      "content_text": "> **TL;DR:** The upgrade order is set not by the end-of-support date but by the system's criticality together with the trigger's type (mandatory, locking, opportunity); the same CVE is an opportunity in an internal tool and mandatory in a payment flow. A 3×3 matrix gives each cell a rank and a response window, and the EOL date is only the ceiling. Because the type drifts over time, the matrix is re-read in every planning round.\n\nAn upgrade queue sorted by date can push the mandatory signal of your most critical system to the bottom.\n\nPicture a queue like this. You have an inventory and you have an EOL list; you merge them and sort by date. At the top sits the row whose EOL is nearest: an internal reporting tool used only by the team. At the bottom sits the row with no date, or the most distant one: a CVE that affects you in the payment flow.\n\nThe sorting worked correctly. What was wrong was what it sorted.\n\n[Part 2](/engineering/notes/upgrade-inventory/) drew the line from the start: the inventory doesn't make decisions, it produces input for the decision matrix. The date is one column of that input, nothing more. Without knowing what a system stops when it goes down, and what type of signal you are holding, a date can't put the queue in order.\n\nThe date is only an upper bound; the order is set by the system's criticality and the trigger's type together.\n\n## The Same CVE, Two Different Cells\n\nSuppose two systems use the same package, and a CVE is published for one component of that package. The two questions from [Part 1](/engineering/notes/upgrade-triggers/) are the tiebreaker here: am I using the affected component, and can the affected code path be reached from outside?\n\n- **Internal reporting tool.** The component is there too, but only the team reaches the tool, and only from the company network. The second answer is \"no\". The signal is an opportunity; a \"not affected\" record is filed.\n- **Payment flow.** The same component sits behind an endpoint reachable from the internet. Both answers are \"yes\". The signal is mandatory.\n\nSame package, same CVE, same severity score. Different order. Severity measures how bad the component is; it doesn't measure what your system would lose if it went down. That's why severity alone doesn't set the order.\n\nType is a property of signal × system: criticality labels the system, and type is the value the signal takes on when it lands on that system. The matrix crosses the two.\n\nThe \"opportunity\" label on the internal tool isn't a permanent verdict either. If the tool is opened to the internet tomorrow, or an exploit is published before a fix arrives, both answers become \"yes\" and the signal moves to mandatory. That's why the record should carry the reasoning, not the result: the sentence \"can't be reached from outside\" also tells you under what condition to look again.\n\n## Three Classes, Three Types, Nine Cells\n\nFirst the axes. Criticality is defined by what the system stops when it goes down. I use three classes:\n\n- **Critical:** stops revenue or the customer flow (payment, login, orders).\n- **Medium:** stops the work of a team or a customer segment, while the main flow continues (admin panel, reporting, integration).\n- **Low:** nobody notices for days when it stops (internal tool, one-off batch).\n\nThe type axis is familiar from Part 1: mandatory, locking, opportunity. The order comes out in two steps: type first, then criticality within the type. The windows in the cells are my recommendation, not an industry standard. Shift them to your team's capacity, but write a window down.\n\n| | Mandatory | Locking | Opportunity |\n|---|---|---|---|\n| **Critical** | **1** · triage the same business day, patch within 7 days; on EOL, at least 3 months before the end date | **4** · into this quarter's plan | **7** · into the quarter's plan if there is a measured gain |\n| **Medium** | **2** · triage within 1 business day, patch within 14 days; on EOL, at least 2 months before the end date | **5** · into next quarter's plan | **8** · backlog |\n| **Low** | **3** · triage within 1 week, patch within 30 days; on EOL, at least 1 month before the end date, or shut the system down | **6** · before the next major | **9** · no date |\n\nPlacing a signal in a cell takes three steps: determine the system's class, take the signal's type from the table in Part 1, and read the rank and window at the intersection. If several signals land in the same cell, the one with the nearer EOL date goes first. Between cells, the date doesn't set the order; it can only narrow the window.\n\nI won't walk through all nine cells one by one; two corners are enough.\n\nCritical × mandatory is rank one: the most expensive system when it goes down, and a signal that can't be made to wait. This is exactly where the row that sank to the bottom of the opening queue belongs. The date column couldn't give it a rank, because a CVE doesn't fit a calendar.\n\nLow × opportunity is rank nine. That doesn't mean \"never do it\", it means \"don't give it a date\": it gets done when you're already in that repo for some other job. The function of rank nine is to keep this work from swelling the queue and slowing down the rank-one job.\n\nThe middle cells sit between the two corners, and this is where most of the arguments start: Medium × mandatory versus Critical × locking. My recommendation is to put the mandatory one first. A mandatory signal's date or exploitation risk moves independently of you; a lock may break nothing today, but it has a budget on a quarterly scale. If the lock's budget is about to run out, breaking this rule is a decision that belongs to you, and the matrix doesn't forbid it.\n\nIf a window and an EOL collide, the EOL wins. The duration in the cell is the rule itself, the EOL date is the ceiling; whichever comes earlier applies. The 30 days of the Low × mandatory cell drops to 20 days if 20 days remain until the end date.\n\nEOL also has a gap between \"upstream is finished\" and \"no fix will come\". Debian 12's EOL date is [12 July 2026](https://wiki.debian.org/DebianReleases); according to the same page, LTS continues until 30 June 2028. If you rely on LTS or on another extended support (ELS) provider, your ceiling is that date. But reading which packages are covered, and writing the note \"relies on LTS\" into the cell, is your job.\n\n## Cells Don't Stay Put\n\nThe matrix is a photograph; signals move. Type drifts over time: an opportunity turns into a locking one, a locking one into a mandatory one. The mechanism is simple: a deferred opportunity narrows the options, and a narrowing option runs into a date.\n\nPicture a medium-criticality system running on PHP 8.2. When a new major version of a package you use comes out, moving to it is an opportunity; the old major still works, nothing breaks. When the package stops shipping fixes to the old major, the same job turns into a locking one. If a security fix arrives only in the new major, the lock turns into a mandatory one.\n\nThe runtime row doesn't walk this path, because on the day the EOL date is published the signal is already mandatory. [php.net](https://www.php.net/supported-versions.php) says 8.2's security support ends on **31 December 2026**; that is 53 days after this post's publication date. The Medium × mandatory cell wants the work finished at least 2 months before the end date; that window closed before this post was published.\n\nTwo clocks run at once in the same system. The [Laravel 12.x release notes](https://laravel.com/docs/12.x/releases) say Laravel 12's security fixes continue until **24 February 2027**. The runtime row and the framework row hit their ceilings 55 days apart. A single \"PHP 8.2\" row squeezes these two ceilings into one date.\n\nThe second axis drifts too, but for a different reason: criticality changes not with time but with the work. An internal tool that opens an endpoint into the payment flow moves from Low to Critical that day. The code stays the same, its class changes.\n\nThe direction of drift is one-way: an opportunity walks toward mandatory on its own and doesn't come back. So a \"we'll look at it later\" decision isn't free; every round moves the cell one step closer to mandatory. A deferred job doesn't stay cheap, it moves toward an expensive date.\n\nThat's why you shouldn't fill in the matrix once and bury it in the queue. In every planning round, re-read each signal's cell. Keep the cell next to the signal (an issue label, a PR description); then drift isn't a surprise, it's the first item of the round.\n\n\n> **Tan:** Write down every decision that breaks the matrix's rule, with its reason and an end date. A job moved up because of a dependency lock should go back to its own cell once the lock is lifted. An exception nobody wrote down will be read as the rule in the next planning round.\n\n\n## The Limit of This Framework\n\nThe matrix gives the order. It doesn't give the target version: whether it's 8.3, 8.4 or 8.5 is decided in Part 4. It doesn't tell you whether you're ready either: your tests, your way back and your dependency map are in Part 5.\n\nBeing first in line doesn't mean being ready to start. The matrix says \"this first\"; it doesn't say \"this today\". If the system at rank one has no tests, the first job may not be the upgrade but writing those tests; Part 5 will draw that distinction.\n\nThe matrix also doesn't tell you, in your place, which class a system falls into. \"Is this system Critical or Medium?\" is the first argument in most teams. If you keep the definition question as \"what stops when it goes down?\", the argument gets shorter: the answer should point to a workflow, not to a product feature.\n\nThe three classes are deliberately coarse. There is no risk score or formula here; a team that needs a formula can split the classes into four, and the logic of the matrix doesn't change.\n\n## Reorder the Queue\n\nBack to the start. The internal reporting tool was at the top, the CVE in the payment flow at the bottom. With the matrix the order flips: payment × mandatory comes first, and the internal tool, even though its EOL is near, drops to third, into its own window. The date didn't take the internal tool out of the queue; it only gave up deciding its position.\n\nA queue that moves in date order makes the work look calm: every row has a day, none of them is wrong. The matrix breaks that calm, because it pulls some rows forward without looking at their date. It's uncomfortable, but it's correct.\n\nThe cost of getting the order wrong is written in [Part 0](/engineering/essays/the-cost-of-deferring-an-upgrade/). [Part 1](/engineering/notes/upgrade-triggers/) sorted the signals into types, and [Part 2](/engineering/notes/upgrade-inventory/) sorted the system into layers. This part turned the two into an order.\n\nA date can be a reason to enter the queue; it isn't enough to set the order.\n\nSort the systems in your inventory into three criticality classes, place the upgrade signals in your queue into the matrix, and take the one in the top cell into this sprint.\n\n## Sources\n\n- [Supported Versions](https://www.php.net/supported-versions.php) — PHP\n- [Laravel 12.x Release Notes](https://laravel.com/docs/12.x/releases) — Laravel\n- [DebianReleases](https://wiki.debian.org/DebianReleases) — Debian",
      "date_published": "2026-11-08T00:00:00.000Z",
      "tags": [
        "dependencies",
        "decisions",
        "security",
        "production",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/managing-technical-debt/",
      "url": "https://muhammetsafak.com/engineering/essays/managing-technical-debt/",
      "title": "Which Technical Debt You Pay, Which You Live With",
      "summary": "What makes technical debt bad is not the principal but the interest: debt in code you touch often and that slows every change gets paid, while ugly code that works and that nobody touches is carried where it stands. Sorting debt by how bad it is and how often it is touched points the limited refactoring budget at the debt that actually charges interest.",
      "content_html": "<p>A backlog had two hundred “technical debt” tickets. The team carried them like a moral failing: “we have to pay all of these off.” Yet most of those two hundred tickets would never charge a single cent of interest over their entire lifetime.</p>\n<p>Technical debt is not a matter of guilt; it is a matter of accounting. And not every debt deserves to be paid off.</p>\n<h2 id=\"technical-debt-is-a-matter-of-accounting\">Technical debt is a matter of accounting</h2>\n<p>The most important part of the debt metaphor is usually skipped: <strong>interest</strong>. What makes a real debt bad is not the principal; it is the interest.</p>\n<p>The same goes for technical debt. Some debts charge interest: they slow you down every time you touch them, make every change harder, eat time every week. Other debts just sit there — they are ugly, but they cost you nothing. Treating the two as the same thing means spending a limited refactor budget in the wrong place.</p>\n<h2 id=\"debt-that-charges-interest\">Debt that charges interest</h2>\n<p>The debt that deserves to be paid off is the kind that charges interest:</p>\n<ul>\n<li>A hot code region touched several times a week slows down every change because it is messy.</li>\n<li>A fragile area has no tests around it and regularly blows up in production.</li>\n<li>An abstraction was drawn wrong and every new feature has to wrestle with it.</li>\n</ul>\n<p>What these have in common: their cost is paid <strong>over and over</strong>. Closing this debt makes every future change cheaper — the investment pays back.</p>\n<h2 id=\"debt-with-no-interest\">Debt with no interest</h2>\n<p>Now the other extreme: ugly but working code in a module no one touches. It hasn’t changed in three years and probably won’t change for three more.</p>\n<p>“Paying off” this debt — that is, refactoring it — means spending budget for zero return. Worse, touching working code carries the risk of new bugs. Debt with no interest isn’t paid off; it is <strong>carried</strong> where it sits.</p>\n<h2 id=\"classifying-debt\">Classifying debt</h2>\n<p>A practical framework places each debt on two axes: <strong>how bad it is</strong> × <strong>how often it’s touched</strong>.</p>\n<ul>\n<li>Very bad + touched often → pay it off now. The interest is high.</li>\n<li>Slightly bad + touched often → fix it as you get the chance, while you’re in there.</li>\n<li>Very bad + rarely touched → document it, contain it, but don’t rush.</li>\n<li>Slightly bad + rarely touched → ignore it. This shouldn’t even be a list item.</li>\n</ul>\n<p>A backlog of two hundred tickets, run through this filter, usually shrinks to twenty real pieces of work.</p>\n<h2 id=\"deliberate-debt-is-also-a-tool\">Deliberate debt is also a tool</h2>\n<p>Debt isn’t always a mistake. Sometimes taking on debt deliberately is the right call: ship fast today, fix it once the idea is validated. This is the “fixing a wrongly drawn boundary is cheap” logic from the <a href=\"https://muhammetsafak.com/engineering/essays/why-i-start-with-a-modular-monolith/\">modular monolith piece</a> — debt that’s cheap to fix, taken on knowingly, and recorded is healthy.</p>\n<p>The dangerous kind is the debt that accumulates unnoticed and quietly eats the complexity budget from the <a href=\"https://muhammetsafak.com/engineering/essays/why-boring-architecture/\">boring architecture</a> piece.</p>\n<hr/>\n<p>Don’t see technical debt as a source of shame; see it as a balance-sheet item. The question isn’t “do we have debt” — every system does. The question is “which one is charging interest.”</p>\n<p>Close the debt that charges interest; live in peace with the rest.</p>",
      "content_text": "> **TL;DR:** What makes technical debt bad is not the principal but the interest: debt in code you touch often and that slows every change gets paid, while ugly code that works and that nobody touches is carried where it stands. Sorting debt by how bad it is and how often it is touched points the limited refactoring budget at the debt that actually charges interest.\n\nA backlog had two hundred \"technical debt\" tickets. The team carried them like a moral failing: \"we have to pay all of these off.\" Yet most of those two hundred tickets would never charge a single cent of interest over their entire lifetime.\n\nTechnical debt is not a matter of guilt; it is a matter of accounting. And not every debt deserves to be paid off.\n\n## Technical debt is a matter of accounting\n\nThe most important part of the debt metaphor is usually skipped: **interest**. What makes a real debt bad is not the principal; it is the interest.\n\nThe same goes for technical debt. Some debts charge interest: they slow you down every time you touch them, make every change harder, eat time every week. Other debts just sit there — they are ugly, but they cost you nothing. Treating the two as the same thing means spending a limited refactor budget in the wrong place.\n\n## Debt that charges interest\n\nThe debt that deserves to be paid off is the kind that charges interest:\n\n- A hot code region touched several times a week slows down every change because it is messy.\n- A fragile area has no tests around it and regularly blows up in production.\n- An abstraction was drawn wrong and every new feature has to wrestle with it.\n\nWhat these have in common: their cost is paid **over and over**. Closing this debt makes every future change cheaper — the investment pays back.\n\n## Debt with no interest\n\nNow the other extreme: ugly but working code in a module no one touches. It hasn't changed in three years and probably won't change for three more.\n\n\"Paying off\" this debt — that is, refactoring it — means spending budget for zero return. Worse, touching working code carries the risk of new bugs. Debt with no interest isn't paid off; it is **carried** where it sits.\n\n## Classifying debt\n\nA practical framework places each debt on two axes: **how bad it is** × **how often it's touched**.\n\n- Very bad + touched often → pay it off now. The interest is high.\n- Slightly bad + touched often → fix it as you get the chance, while you're in there.\n- Very bad + rarely touched → document it, contain it, but don't rush.\n- Slightly bad + rarely touched → ignore it. This shouldn't even be a list item.\n\nA backlog of two hundred tickets, run through this filter, usually shrinks to twenty real pieces of work.\n\n## Deliberate debt is also a tool\n\nDebt isn't always a mistake. Sometimes taking on debt deliberately is the right call: ship fast today, fix it once the idea is validated. This is the \"fixing a wrongly drawn boundary is cheap\" logic from the [modular monolith piece](/engineering/essays/why-i-start-with-a-modular-monolith/) — debt that's cheap to fix, taken on knowingly, and recorded is healthy.\n\nThe dangerous kind is the debt that accumulates unnoticed and quietly eats the complexity budget from the [boring architecture](/engineering/essays/why-boring-architecture/) piece.\n\n---\n\nDon't see technical debt as a source of shame; see it as a balance-sheet item. The question isn't \"do we have debt\" — every system does. The question is \"which one is charging interest.\"\n\nClose the debt that charges interest; live in peace with the rest.",
      "date_published": "2026-11-07T00:00:00.000Z",
      "tags": [
        "technical-debt",
        "decisions",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-inventory/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-inventory/",
      "title": "Upgrade Inventory: A Chain of Layers, Not a Version",
      "summary": "A system is not defined by one version number but by six layers, from the runtime to the CI runner, and each layer's support ends on a different date. The layer whose support ends first sets the upgrade date. An inventory that records the running version, where it is read, the end date and the lock for each layer shows which layer holds the lock before anything breaks.",
      "content_html": "<p>“We’re on PHP 8.1” is not an inventory, it’s the name of one of six layers.</p>\n<p>The sentence sounds like a status report, because a single number seems to answer the question. It doesn’t. That number is the runtime’s version. Around it sit five more layers, each with its own version and its own support calendar: extensions, framework, packages, container image and CI runner. Which upgrade you need is told by the sum of those six, not by the name of one.</p>\n<p>In a system managed by a version number, the lock only shows up when something breaks: the build fails, <code>composer update</code> rejects a package, the image doesn’t bring the PHP you expected. The question changes that day from “when do we upgrade” to “why can’t we”. The answer is written in the inventory; if no inventory was drawn up, it gets read for the first time that day.</p>\n<p>The lock is most often in a layer you never wrote down: the 7.1 lock in <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/\">Part 0</a> was not in the runtime, it was in the package layer.</p>\n<h2 id=\"six-layers-one-chain\">Six Layers, One Chain</h2>\n<p>A package sets that lock with a single line: <code>require.php</code> in <code>composer.json</code> leaves the question of which version the runtime can move to in the package author’s hands.</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"json\"><code><span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">{</span></span>\n<span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">  &quot;require&quot;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">: {</span></span>\n<span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">    &quot;php&quot;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">: </span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&quot;^8.1&quot;</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">  }</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">}</span></span></code></pre>\n<p>That line limits the PHP version of every project that installs the package. A line in the Dockerfile does the same job one layer below:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"dockerfile\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> php:8.2-fpm-bookworm</span></span></code></pre>\n<p><code>FROM</code> pins both the PHP version and the operating system version beneath it. The chain covers everything that sits between these two lines:</p>\n<ol>\n<li><strong>Runtime.</strong> PHP itself. The ceiling and the floor of the other five layers pass through here.</li>\n<li><strong>Extensions.</strong> Modules compiled into the runtime or loaded later. Their versions depend on the runtime; which ones the project wants is told by the <code>ext-*</code> entries in <code>composer.json</code>/<code>composer.lock</code> (or by <code>composer check-platform-reqs</code>), while <code>composer show --platform</code> lists only what is installed in the environment where the command runs.</li>\n</ol>\n<p>Two layers, two constraints: the runtime decides which extension versions will work, and you can’t move to a PHP that an extension doesn’t support.</p>\n<ol start=\"3\">\n<li><strong>Framework.</strong> Laravel 12 requires PHP 8.2–8.5. The framework limits the runtime from above and from below.</li>\n<li><strong>Packages.</strong> The <code>require.php</code> line above. Every package has its own lower and upper bound; the intersection of all of them is the range your runtime can move within.</li>\n</ol>\n<p>The relationship between framework and packages runs both ways too: the framework’s major decides which package versions can be installed, and if one of the packages stays old, it blocks the move to the framework.</p>\n<ol start=\"5\">\n<li><strong>Container image.</strong> The <code>FROM</code> line. Because its version is written down as a tag, it is the easiest layer to read and the easiest to forget; once an image is built, the PHP and operating system inside it age even if your code doesn’t change.</li>\n<li><strong>CI runner.</strong> The environment that runs the tests and builds the image. It has its own image, its own version, its own retirement date.</li>\n</ol>\n<p>Below that sit the operating system kernel and the database server, and both have their own calendars. You can add them to the list as a seventh and eighth row, but I’m staying with six layers here.</p>\n<p>What the chain does is this: if one layer can’t move, the neighbors it constrains can’t either. What stops an upgrade is often not the top or the bottom layer, but a link sitting quietly somewhere in the middle.</p>\n<h2 id=\"the-earliest-ending-layer-sets-the-date\">The Earliest-Ending Layer Sets the Date</h2>\n<p>Each layer’s clock runs separately and none waits for another. The dates below come from official pages; each belongs to a different layer.</p>\n<ul>\n<li><strong>Runtime.</strong> The <a href=\"https://www.php.net/supported-versions.php\">php.net</a> policy is 2+2: two years of active support, two years of security only. PHP 8.2’s security support ends on <strong>31 December 2026</strong>.</li>\n<li><strong>Framework.</strong> According to the <a href=\"https://laravel.com/docs/12.x/releases\">Laravel 12.x release notes</a>, security fixes for Laravel 12 continue until <strong>24 February 2027</strong>. The same page says Laravel 12 requires PHP 8.2–8.5 and Laravel 13 requires PHP 8.3–8.5.</li>\n<li><strong>Container image.</strong> <a href=\"https://wiki.debian.org/DebianReleases\">Debian 12’s</a> EOL date is <strong>12 July 2026</strong>; LTS support runs until <strong>30 June 2028</strong>. Debian 13 was released on 9 August 2025.</li>\n<li><strong>CI runner.</strong> GitHub announced that the <code>ubuntu-20.04</code> runner image <a href=\"https://github.blog/changelog/2025-01-15-github-actions-ubuntu-20-runner-image-brownout-dates-and-other-breaking-changes/\">would be fully retired on 15 April 2025</a>.</li>\n</ul>\n<p>The rule that comes out of this list is simple: <strong>the upgrade date is set not by the average but by the support that ends earliest.</strong> Here that layer is PHP 8.2: 31 December 2026 comes before Laravel 12’s 24 February 2027. Even if the framework’s support continues, the runtime’s support will have ended, and moving to Laravel 13 requires leaving PHP 8.2 behind anyway.</p>\n<p>EOL shouldn’t be exaggerated. Upstream support ending doesn’t mean no fix will ever arrive; Debian 12 moving to LTS is an example. But whether a fix arrives now depends on a distribution’s or a vendor’s calendar, and reading what it covers is your job. The inventory puts this distinction in writing: in the end date column, write the upstream date, and next to it the distribution’s extended date if there is one; don’t mix the two in one cell.</p>\n<p>The runner row deserves a separate pause. In the other layers a date is a warning; here, once the image is retired, the <code>runs-on</code> value can no longer find that image, no runner is assigned to the job, and it often waits in the queue without even throwing an error. That makes the CI layer the row that comes to mind last but can get expensive first.</p>\n<h2 id=\"the-inventory-six-rows-five-columns\">The Inventory: Six Rows, Five Columns</h2>\n<p>The template is this: layer, running version, where it is read, end of support, what it locks. Six layers, six rows; if you add a layer, add a row, not a column. The order of the columns is also a reading order: if you write the version first and then where you read it from, someone else can verify the table from the same sources.</p>\n<p>The filled-in version below is for a hypothetical system. I picked only versions whose dates I verified; the package row is deliberately left empty, because that row will be filled from your own lock file.</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Layer</th><th>Running version</th><th>Where it is read</th><th>End of support</th><th>What it locks</th></tr></thead><tbody><tr><td>Runtime</td><td>PHP 8.2</td><td><code>FROM</code> line, <code>php -v</code></td><td>security 31 December 2026</td><td>the move to Laravel 13: 13 requires PHP 8.3–8.5</td></tr><tr><td>Extension</td><td><code>ext-*</code> entries</td><td><code>composer.lock</code>, <code>composer check-platform-reqs</code></td><td>same as the runtime for core; the package’s repository for PECL</td><td>the version the runtime can move to</td></tr><tr><td>Framework</td><td>Laravel 12</td><td><code>composer.lock</code></td><td>security 24 February 2027</td><td>the runtime to the PHP 8.2–8.5 range</td></tr><tr><td>Package</td><td>from your own lock file</td><td><code>composer.lock</code>, the package’s <code>composer.json</code></td><td>from the package’s repository; “unknown” if there is no date</td><td>runtime and framework (the case in Part 0)</td></tr><tr><td>Container image</td><td>Debian 12 based (<code>bookworm</code>)</td><td><code>Dockerfile</code> <code>FROM</code></td><td>EOL 12 July 2026, LTS 30 June 2028</td><td>the runtime version and the operating system packages</td></tr><tr><td>CI runner</td><td>your <code>runs-on</code> value</td><td><code>.github/workflows/*.yml</code></td><td>from GitHub’s runner announcement</td><td>the build itself</td></tr></tbody></table></div>\n<p>The “where it is read” cell of three rows points to the same file, <code>composer.lock</code>. That’s the good news: half of the inventory is already written in files you have. The bad news is that the other half, the image and the runner, is often written down nowhere as a whole, because there is no lock file for it.</p>\n<p>“Unknown” is a valid answer. The difference between an empty cell and “unknown” is that the second one gets queued as a job.</p>\n<p>The last step of the table is to mark the earliest date in the end of support column. In the example there are two candidates: Debian 12’s 12 July 2026 and PHP 8.2’s 31 December 2026. The first extends to 2028 with LTS for the image’s operating system layer, the second doesn’t extend for the runtime. Which date you take as the basis (EOL or LTS) is a decision; the inventory writes both and doesn’t choose.</p>\n<blockquote><p><strong>Tan:</strong> Filling in the inventory once is easy; keeping it current when the FROM line or the runs-on value changes is the hard part. Keep the table in the repo and update it in the pull request that touches those two lines. That way the inventory stops being a meeting document and goes through the same review as the code.</p></blockquote>\n<h2 id=\"the-limit-of-this-framework\">The Limit of This Framework</h2>\n<p>The inventory doesn’t make decisions, it produces input for the decision matrix. Filling in six rows doesn’t mean “upgrade now”; it means making visible what locks what, and by which date.</p>\n<p>In which system, with what risk, in what order you’ll proceed is the decision matrix’s job: Part 3 of the series. How to choose the target version is in Part 4, and the prerequisites and testing before the upgrade are in Part 5.</p>\n<p>There is one more thing: an end-of-support date is the provider’s calendar, not your risk. The same date goes into a queue for an internal tool and onto the calendar for a payment flow. A date is an upper bound, not urgency. Which signal is mandatory was sorted out in <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-triggers/\">Part 1</a>; this part listed the layers those signals come from.</p>\n<h2 id=\"back-to-were-on-php-81\">Back to “We’re on PHP 8.1”</h2>\n<p>The sentence isn’t wrong, it’s incomplete. It names one of six layers and hides that the lock is most often not in that layer.</p>\n<p>The inventory fixes this in two moves: you write down the running version for each layer, then you put the end-of-support dates side by side and mark the earliest. That date is the one that starts the countdown of the upgrade plan; the remaining five rows show what that countdown will collide with.</p>\n<p>We’ll use this input in the coming parts: the decision matrix in Part 3, the target version in Part 4, the prerequisites in Part 5.</p>\n<p>Pick one of your systems; for each of the six layers, write the running version and the end-of-support date on a single row, and mark the earliest date.</p>",
      "content_text": "> **TL;DR:** A system is not defined by one version number but by six layers, from the runtime to the CI runner, and each layer's support ends on a different date. The layer whose support ends first sets the upgrade date. An inventory that records the running version, where it is read, the end date and the lock for each layer shows which layer holds the lock before anything breaks.\n\n\"We're on PHP 8.1\" is not an inventory, it's the name of one of six layers.\n\nThe sentence sounds like a status report, because a single number seems to answer the question. It doesn't. That number is the runtime's version. Around it sit five more layers, each with its own version and its own support calendar: extensions, framework, packages, container image and CI runner. Which upgrade you need is told by the sum of those six, not by the name of one.\n\nIn a system managed by a version number, the lock only shows up when something breaks: the build fails, `composer update` rejects a package, the image doesn't bring the PHP you expected. The question changes that day from \"when do we upgrade\" to \"why can't we\". The answer is written in the inventory; if no inventory was drawn up, it gets read for the first time that day.\n\nThe lock is most often in a layer you never wrote down: the 7.1 lock in [Part 0](/engineering/essays/the-cost-of-deferring-an-upgrade/) was not in the runtime, it was in the package layer.\n\n## Six Layers, One Chain\n\nA package sets that lock with a single line: `require.php` in `composer.json` leaves the question of which version the runtime can move to in the package author's hands.\n\n```json\n{\n  \"require\": {\n    \"php\": \"^8.1\"\n  }\n}\n```\n\nThat line limits the PHP version of every project that installs the package. A line in the Dockerfile does the same job one layer below:\n\n```dockerfile\nFROM php:8.2-fpm-bookworm\n```\n\n`FROM` pins both the PHP version and the operating system version beneath it. The chain covers everything that sits between these two lines:\n\n1. **Runtime.** PHP itself. The ceiling and the floor of the other five layers pass through here.\n2. **Extensions.** Modules compiled into the runtime or loaded later. Their versions depend on the runtime; which ones the project wants is told by the `ext-*` entries in `composer.json`/`composer.lock` (or by `composer check-platform-reqs`), while `composer show --platform` lists only what is installed in the environment where the command runs.\n\nTwo layers, two constraints: the runtime decides which extension versions will work, and you can't move to a PHP that an extension doesn't support.\n\n3. **Framework.** Laravel 12 requires PHP 8.2–8.5. The framework limits the runtime from above and from below.\n4. **Packages.** The `require.php` line above. Every package has its own lower and upper bound; the intersection of all of them is the range your runtime can move within.\n\nThe relationship between framework and packages runs both ways too: the framework's major decides which package versions can be installed, and if one of the packages stays old, it blocks the move to the framework.\n\n5. **Container image.** The `FROM` line. Because its version is written down as a tag, it is the easiest layer to read and the easiest to forget; once an image is built, the PHP and operating system inside it age even if your code doesn't change.\n6. **CI runner.** The environment that runs the tests and builds the image. It has its own image, its own version, its own retirement date.\n\nBelow that sit the operating system kernel and the database server, and both have their own calendars. You can add them to the list as a seventh and eighth row, but I'm staying with six layers here.\n\nWhat the chain does is this: if one layer can't move, the neighbors it constrains can't either. What stops an upgrade is often not the top or the bottom layer, but a link sitting quietly somewhere in the middle.\n\n## The Earliest-Ending Layer Sets the Date\n\nEach layer's clock runs separately and none waits for another. The dates below come from official pages; each belongs to a different layer.\n\n- **Runtime.** The [php.net](https://www.php.net/supported-versions.php) policy is 2+2: two years of active support, two years of security only. PHP 8.2's security support ends on **31 December 2026**.\n- **Framework.** According to the [Laravel 12.x release notes](https://laravel.com/docs/12.x/releases), security fixes for Laravel 12 continue until **24 February 2027**. The same page says Laravel 12 requires PHP 8.2–8.5 and Laravel 13 requires PHP 8.3–8.5.\n- **Container image.** [Debian 12's](https://wiki.debian.org/DebianReleases) EOL date is **12 July 2026**; LTS support runs until **30 June 2028**. Debian 13 was released on 9 August 2025.\n- **CI runner.** GitHub announced that the `ubuntu-20.04` runner image [would be fully retired on 15 April 2025](https://github.blog/changelog/2025-01-15-github-actions-ubuntu-20-runner-image-brownout-dates-and-other-breaking-changes/).\n\nThe rule that comes out of this list is simple: **the upgrade date is set not by the average but by the support that ends earliest.** Here that layer is PHP 8.2: 31 December 2026 comes before Laravel 12's 24 February 2027. Even if the framework's support continues, the runtime's support will have ended, and moving to Laravel 13 requires leaving PHP 8.2 behind anyway.\n\nEOL shouldn't be exaggerated. Upstream support ending doesn't mean no fix will ever arrive; Debian 12 moving to LTS is an example. But whether a fix arrives now depends on a distribution's or a vendor's calendar, and reading what it covers is your job. The inventory puts this distinction in writing: in the end date column, write the upstream date, and next to it the distribution's extended date if there is one; don't mix the two in one cell.\n\nThe runner row deserves a separate pause. In the other layers a date is a warning; here, once the image is retired, the `runs-on` value can no longer find that image, no runner is assigned to the job, and it often waits in the queue without even throwing an error. That makes the CI layer the row that comes to mind last but can get expensive first.\n\n## The Inventory: Six Rows, Five Columns\n\nThe template is this: layer, running version, where it is read, end of support, what it locks. Six layers, six rows; if you add a layer, add a row, not a column. The order of the columns is also a reading order: if you write the version first and then where you read it from, someone else can verify the table from the same sources.\n\nThe filled-in version below is for a hypothetical system. I picked only versions whose dates I verified; the package row is deliberately left empty, because that row will be filled from your own lock file.\n\n| Layer | Running version | Where it is read | End of support | What it locks |\n|---|---|---|---|---|\n| Runtime | PHP 8.2 | `FROM` line, `php -v` | security 31 December 2026 | the move to Laravel 13: 13 requires PHP 8.3–8.5 |\n| Extension | `ext-*` entries | `composer.lock`, `composer check-platform-reqs` | same as the runtime for core; the package's repository for PECL | the version the runtime can move to |\n| Framework | Laravel 12 | `composer.lock` | security 24 February 2027 | the runtime to the PHP 8.2–8.5 range |\n| Package | from your own lock file | `composer.lock`, the package's `composer.json` | from the package's repository; \"unknown\" if there is no date | runtime and framework (the case in Part 0) |\n| Container image | Debian 12 based (`bookworm`) | `Dockerfile` `FROM` | EOL 12 July 2026, LTS 30 June 2028 | the runtime version and the operating system packages |\n| CI runner | your `runs-on` value | `.github/workflows/*.yml` | from GitHub's runner announcement | the build itself |\n\nThe \"where it is read\" cell of three rows points to the same file, `composer.lock`. That's the good news: half of the inventory is already written in files you have. The bad news is that the other half, the image and the runner, is often written down nowhere as a whole, because there is no lock file for it.\n\n\"Unknown\" is a valid answer. The difference between an empty cell and \"unknown\" is that the second one gets queued as a job.\n\nThe last step of the table is to mark the earliest date in the end of support column. In the example there are two candidates: Debian 12's 12 July 2026 and PHP 8.2's 31 December 2026. The first extends to 2028 with LTS for the image's operating system layer, the second doesn't extend for the runtime. Which date you take as the basis (EOL or LTS) is a decision; the inventory writes both and doesn't choose.\n\n\n> **Tan:** Filling in the inventory once is easy; keeping it current when the FROM line or the runs-on value changes is the hard part. Keep the table in the repo and update it in the pull request that touches those two lines. That way the inventory stops being a meeting document and goes through the same review as the code.\n\n\n## The Limit of This Framework\n\nThe inventory doesn't make decisions, it produces input for the decision matrix. Filling in six rows doesn't mean \"upgrade now\"; it means making visible what locks what, and by which date.\n\nIn which system, with what risk, in what order you'll proceed is the decision matrix's job: Part 3 of the series. How to choose the target version is in Part 4, and the prerequisites and testing before the upgrade are in Part 5.\n\nThere is one more thing: an end-of-support date is the provider's calendar, not your risk. The same date goes into a queue for an internal tool and onto the calendar for a payment flow. A date is an upper bound, not urgency. Which signal is mandatory was sorted out in [Part 1](/engineering/notes/upgrade-triggers/); this part listed the layers those signals come from.\n\n## Back to \"We're on PHP 8.1\"\n\nThe sentence isn't wrong, it's incomplete. It names one of six layers and hides that the lock is most often not in that layer.\n\nThe inventory fixes this in two moves: you write down the running version for each layer, then you put the end-of-support dates side by side and mark the earliest. That date is the one that starts the countdown of the upgrade plan; the remaining five rows show what that countdown will collide with.\n\nWe'll use this input in the coming parts: the decision matrix in Part 3, the target version in Part 4, the prerequisites in Part 5.\n\nPick one of your systems; for each of the six layers, write the running version and the end-of-support date on a single row, and mark the earliest date.\n\n## Sources\n\n- [Supported Versions](https://www.php.net/supported-versions.php) — PHP\n- [Laravel 12.x Release Notes](https://laravel.com/docs/12.x/releases) — Laravel\n- [DebianReleases](https://wiki.debian.org/DebianReleases) — Debian\n- [GitHub Actions: Ubuntu 20 runner image brownout dates and other breaking changes](https://github.blog/changelog/2025-01-15-github-actions-ubuntu-20-runner-image-brownout-dates-and-other-breaking-changes/) — GitHub",
      "date_published": "2026-11-01T00:00:00.000Z",
      "tags": [
        "dependencies",
        "decisions",
        "production",
        "devops",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/abstraction-inflation/",
      "url": "https://muhammetsafak.com/engineering/essays/abstraction-inflation/",
      "title": "Stop Writing Interfaces With a Single Implementation",
      "summary": "A single-implementation interface is a mechanical misreading of \"program to an interface\": it makes navigation indirect, splits reading across two files and promises flexibility that never arrives. An interface earns its cost with several real implementations, an external boundary or a test seam that is actually used. When a second implementation arrives, extract interface is a few minutes of work.",
      "content_html": "<p>On one project, every class had a twin: <code>UserService</code> and <code>UserServiceInterface</code>, <code>OrderRepository</code> and <code>OrderRepositoryInterface</code>. Each interface had exactly one implementation. The folder count had doubled; the flexibility gained was zero.</p>\n<p>The single-implementation interface is the most common speculative abstraction — and it’s usually the result of a misread principle.</p>\n<h2 id=\"program-to-an-interface-is-being-misread\">“Program to an interface” is being misread</h2>\n<p>The principle “program to an interface, not an implementation” has been repeated for years. But the word “interface” in the principle is not the <code>interface</code> keyword in PHP.</p>\n<p>What the principle says is this: depend on a type’s <strong>contract</strong>, not its <strong>internal details</strong>. A class’s public methods are already its contract — which means a concrete class is, conceptually, already an “interface.” Reading the principle as “open an <code>interface</code> file for every class” turns a design idea into a mechanical ritual.</p>\n<h2 id=\"what-a-single-implementation-interface-costs\">What a single-implementation interface costs</h2>\n<p>An empty abstraction isn’t free:</p>\n<ul>\n<li><strong>Navigation gets indirect.</strong> “Go to definition” takes you to the interface, not the code. To see the actual logic you take one more step — every time.</li>\n<li><strong>Reading gets harder.</strong> To understand a behavior you open two files: what was promised and what was done. A single concrete class would have kept both together.</li>\n<li><strong>A false promise of flexibility.</strong> The interface says “this can change.” But it won’t; the single implementation stays single for years.</li>\n</ul>\n<p>This is one of the red flags I listed in <a href=\"https://muhammetsafak.com/engineering/essays/signals-of-an-over-complex-system/\">signals of an over-complex system</a>.</p>\n<h2 id=\"when-abstraction-is-free\">When abstraction is free</h2>\n<p>An interface earns its cost if it does real work. The places it’s genuinely needed:</p>\n<ul>\n<li><strong>Multiple implementations actually exist.</strong> Two payment providers, two storage backends — two concrete things that exist today.</li>\n<li><strong>There’s a real external boundary.</strong> The line between your application and a world it doesn’t control — an external API, an SDK. Here the interface is a buffer.</li>\n<li><strong>There’s a test seam you actually use.</strong> To swap a costly, slow dependency you can’t control — a payment gateway — for a fake in tests. But don’t abstract everything on this pretext, like <a href=\"https://muhammetsafak.com/engineering/essays/integration-vs-unit-tests/\">mocking your own database</a>.</li>\n</ul>\n<p>The common thread: all three are needs that <strong>exist today</strong>. Not “just in case.”</p>\n<h2 id=\"opening-the-seam-later-is-cheap\">Opening the seam later is cheap</h2>\n<p>The objection I hear most: “what if a second implementation shows up later?” If it does, pulling the interface out that day is an IDE refactor — “extract interface,” a few minutes. The asymmetry from <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-just-in-case-code/\">the cost of just-in-case code</a> holds here too: extracting an interface from a concrete class is easy; tearing out an unnecessary interface is hard.</p>\n<p>Until a second implementation arrives, use the concrete class directly. The code is shorter, more readable, and exactly as complex as reality demands — no more.</p>\n<hr/>\n<p>A single-implementation interface is a layer added without a problem to solve. It looks like “good design”; it’s really the prepayment of a decision you could have deferred.</p>\n<p>The second implementation is what writes the interface — not the possibility of one.</p>",
      "content_text": "> **TL;DR:** A single-implementation interface is a mechanical misreading of \"program to an interface\": it makes navigation indirect, splits reading across two files and promises flexibility that never arrives. An interface earns its cost with several real implementations, an external boundary or a test seam that is actually used. When a second implementation arrives, extract interface is a few minutes of work.\n\nOn one project, every class had a twin: `UserService` and `UserServiceInterface`, `OrderRepository` and `OrderRepositoryInterface`. Each interface had exactly one implementation. The folder count had doubled; the flexibility gained was zero.\n\nThe single-implementation interface is the most common speculative abstraction — and it's usually the result of a misread principle.\n\n## \"Program to an interface\" is being misread\n\nThe principle \"program to an interface, not an implementation\" has been repeated for years. But the word \"interface\" in the principle is not the `interface` keyword in PHP.\n\nWhat the principle says is this: depend on a type's **contract**, not its **internal details**. A class's public methods are already its contract — which means a concrete class is, conceptually, already an \"interface.\" Reading the principle as \"open an `interface` file for every class\" turns a design idea into a mechanical ritual.\n\n## What a single-implementation interface costs\n\nAn empty abstraction isn't free:\n\n- **Navigation gets indirect.** \"Go to definition\" takes you to the interface, not the code. To see the actual logic you take one more step — every time.\n- **Reading gets harder.** To understand a behavior you open two files: what was promised and what was done. A single concrete class would have kept both together.\n- **A false promise of flexibility.** The interface says \"this can change.\" But it won't; the single implementation stays single for years.\n\nThis is one of the red flags I listed in [signals of an over-complex system](/engineering/essays/signals-of-an-over-complex-system/).\n\n## When abstraction is free\n\nAn interface earns its cost if it does real work. The places it's genuinely needed:\n\n- **Multiple implementations actually exist.** Two payment providers, two storage backends — two concrete things that exist today.\n- **There's a real external boundary.** The line between your application and a world it doesn't control — an external API, an SDK. Here the interface is a buffer.\n- **There's a test seam you actually use.** To swap a costly, slow dependency you can't control — a payment gateway — for a fake in tests. But don't abstract everything on this pretext, like [mocking your own database](/engineering/essays/integration-vs-unit-tests/).\n\nThe common thread: all three are needs that **exist today**. Not \"just in case.\"\n\n## Opening the seam later is cheap\n\nThe objection I hear most: \"what if a second implementation shows up later?\" If it does, pulling the interface out that day is an IDE refactor — \"extract interface,\" a few minutes. The asymmetry from [the cost of just-in-case code](/engineering/essays/the-cost-of-just-in-case-code/) holds here too: extracting an interface from a concrete class is easy; tearing out an unnecessary interface is hard.\n\nUntil a second implementation arrives, use the concrete class directly. The code is shorter, more readable, and exactly as complex as reality demands — no more.\n\n---\n\nA single-implementation interface is a layer added without a problem to solve. It looks like \"good design\"; it's really the prepayment of a decision you could have deferred.\n\nThe second implementation is what writes the interface — not the possibility of one.",
      "date_published": "2026-10-31T00:00:00.000Z",
      "tags": [
        "architecture",
        "simplicity",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/upgrade-triggers/",
      "url": "https://muhammetsafak.com/engineering/notes/upgrade-triggers/",
      "title": "Upgrade Triggers: Mandatory, Locking, Opportunity",
      "summary": "A Dependabot PR, an EOL notice, a deprecation warning and a CVE bulletin land in the same queue but not with the same urgency. EOL and a CVE that affects you are mandatory, a dependency lock and a deprecation are locking, and features and performance are opportunity. Writing a response time for each type keeps you from rushing a reminder and from being late to a lock.",
      "content_html": "<p>Most of the PRs Dependabot opens are not obligations, they are reminders.</p>\n<p>Four kinds of signal get mixed together in the queue: Dependabot PRs, deprecation warnings, EOL announcements and CVE bulletins. Each comes from a different source for a different reason, but all of them land on the same list in the same tone. The screen looks the same; the work is not the same size.</p>\n<p>What is mandatory comes from somewhere else: an EOL date, a CVE, or a dependency that locks you to an old version. A team that reacts to all three the same way is either late or running for nothing.</p>\n<h2 id=\"two-different-clocks-drop-into-the-queue\">Two Different Clocks Drop Into the Queue</h2>\n<p>How urgent a PR is doesn’t say in its title; it says in which clock opened it: one is tied to an advisory, the other to the schedule in <code>dependabot.yml</code>.</p>\n<p>According to GitHub’s documentation, when security updates are enabled, a new PR is opened when a dependency with a vulnerability is found. Version updates, on the other hand, are opened when a new version is released and run at the frequency you define in <code>dependabot.yml</code>. The first is triggered by something in the outside world, the second by a schedule you wrote.</p>\n<p>One more detail: the <code>cooldown</code> setting delays PR creation for version updates only; it doesn’t apply to security updates. So the setting you put in place to cut PR noise doesn’t silence a security PR.</p>\n<p>The practical consequence: a version update PR that arrives on a weekly schedule sits in the same queue as a PR born from an advisory, but it is not the same clock’s job. You can deal with one this week and the other this quarter.</p>\n<p>Before you open a PR, look at two things: who opened it, and which label it came with. If it’s a security update, the question is no longer the version difference but whether you are affected. If it’s a version update, the question is whether that version fixes anything. The answer to the second will most often be “no, a new version came out, that’s all.”</p>\n<h2 id=\"eol-is-a-date-a-cve-is-an-event\">EOL Is a Date, a CVE Is an Event</h2>\n<p>EOL is known in advance. <a href=\"https://www.php.net/supported-versions.php\">php.net</a> publishes the end date of security support for each branch, and the policy is simple: two years of active support from release, then two years of security fixes only. PHP 8.2’s security support ends on <strong>31 December 2026</strong>. That is about 9.5 weeks after this post’s publication date.</p>\n<p>The framework layer keeps its own clock too. Laravel’s <a href=\"https://laravel.com/docs/12.x/releases\">12.x release notes</a> say: bug fixes are provided for 18 months, security fixes for 2 years. For Laravel 12, that means bug fixes ended on 13 August 2026 and security fixes continue until 24 February 2027. So a team running Laravel 12 on the day this post is published has already lost bug fix support, but has not yet lost security support.</p>\n<p>A CVE doesn’t keep to a calendar. It can show up on a Tuesday morning, and it doesn’t care which version you run.</p>\n<p>The aftermath of EOL shouldn’t be exaggerated either. Upstream support ending doesn’t mean no fix will ever arrive; it means whether one arrives is no longer in your control. Ubuntu’s <a href=\"https://ubuntu.com/security/notices/USN-6305-2\">USN-6305-2</a> bulletin is an example: upstream support for PHP 7.4 had ended in November 2022; on 27 February 2024, Ubuntu released fixes to its PHP packages for CVE-2023-3823 and CVE-2023-3824. <code>php7.4</code> on 20.04 got it from the standard repository; <code>php7.2</code> on 18.04 and <code>php7.0</code> on 16.04 required ESM and Ubuntu Pro.</p>\n<p>That can be a way out. But the price is staying tied to a vendor, and leaving the question of which package the fix comes in and how fast to their schedule.</p>\n<p>The value of an EOL date is that it is predictable. You can count the date backwards: set the line by which you want to be in production before the end date, and count back from there to staging, and from there to the test work. If I applied my recommendation below to 8.2, the line would be 30 September 2026. If you are still running 8.2 as you read this, that line has passed; this is not an accusation, it’s the reason to write the plan today.</p>\n<h2 id=\"the-locking-trigger-is-invisible\">The Locking Trigger Is Invisible</h2>\n<p>A locking trigger carries neither a date nor a bulletin. When a package stops supporting the old runtime, its new version becomes impossible to install, and nobody tells you.</p>\n<p>In the PHP 7.1 case, the trigger wasn’t EOL, it was a dependency lock; the details are in <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/\">The Cost of Deferring an Upgrade</a>.</p>\n<p>Since a lock has no date like an EOL, you have to measure it: of the pending package updates, how many can’t be installed because of your runtime version? Every number above zero shows that a door has closed.</p>\n<p>The lock grows quietly. Because everything keeps working on the old runtime, it raises no alarm; the first visible signal is the day the package you want to update can’t be installed. On that day the type is no longer opportunity but locking, and the way out is likely to be a single piece.</p>\n<h2 id=\"three-types-three-response-times\">Three Types, Three Response Times</h2>\n<p>I sort signals into three types:</p>\n<ul>\n<li><strong>Mandatory:</strong> a signal that comes from outside and whose date or risk is independent of your preference (EOL, a CVE that affects you).</li>\n<li><strong>Locking:</strong> a signal that breaks nothing today but narrows your options tomorrow.</li>\n<li><strong>Opportunity:</strong> a signal where nothing breaks if you don’t act, and you gain something if you do.</li>\n</ul>\n<p>The response times below are my recommendation. They are not an industry standard; shift them to your own team’s capacity, but write a time down. A signal with no time sits in the queue, and a signal that sits in the queue eventually comes back as “urgent.”</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Signal</th><th>Type</th><th>Response time (my recommendation)</th></tr></thead><tbody><tr><td>A CVE that affects you</td><td>Mandatory</td><td>Triage the same business day, patch within days</td></tr><tr><td>A CVE that doesn’t affect you</td><td>Opportunity</td><td>Normal cycle; the record that you’re not affected is kept</td></tr><tr><td>EOL date</td><td>Mandatory</td><td>The date goes on the calendar; in production at least 3 months before the end date</td></tr><tr><td>Dependency lock</td><td>Locking</td><td>Goes into next quarter’s plan</td></tr><tr><td>Deprecation warning</td><td>Locking</td><td>Before the next major</td></tr><tr><td>Feature or performance</td><td>Opportunity</td><td>Backlog; no date unless there’s a measured gain</td></tr></tbody></table></div>\n<p>Two rows of the table deserve a separate pause. First, the CVE: the same bulletin is mandatory if it touches a code path you use, and an opportunity if it doesn’t. The urgency is set not by the bulletin’s headline but by your system. Two questions are enough to settle it: am I using the affected component, and can the affected code path be reached from outside? If you answer “yes” to both, you are on the first row of the table; if the fix hasn’t reached your version branch yet, this doesn’t extend the time, it turns the job from patching into a temporary mitigation. If one of the answers is “no,” put that on record; the record keeps you from debating the same bulletin again a month later. Second, performance: “the new version is faster” is an opportunity, not an obligation. Don’t open a calendar slot on that sentence without measuring.</p>\n<p>Why is the time a quarter rather than days on the locking rows? Because a lock breaks nothing today; but if one more package drops the old runtime every quarter, the cost of the way out grows. A quarter is short enough to notice that and write it into the next planning.</p>\n<blockquote><p><strong>Tan:</strong> Write the type and the response time where the signal lives, not in a separate doc: a label on the issue or one line in the PR description is enough. Whoever triages the queue then reads the decision from the list itself instead of opening a wiki. The \"not affected\" note lives there too, so when the same advisory comes back a month later, the answer is already attached.</p></blockquote>\n<h2 id=\"the-limit-of-this-framework\">The Limit of This Framework</h2>\n<p>This classification doesn’t replace a decision matrix. The type tells you the upper bound of urgency; it doesn’t tell you in which system, with what risk, in what order the work will be done.</p>\n<p>The same CVE can be an opportunity in an internal tool and mandatory in a payment flow. What makes that distinction is how critical the system is. The decision matrix is in part 3 of the series.</p>\n<p>The type is also not fixed. An opportunity, as it is deferred, turns into a locking one; a lock, as the EOL date approaches, turns into a mandatory one. Don’t classify once and bury it in the queue; look again in every planning round.</p>\n<h2 id=\"back-to-the-queue\">Back to the Queue</h2>\n<p>Back to the start: that Dependabot PR. Which clock opened it? An advisory, or a schedule? Is it releasing a lock, or only telling you a new version came out? Three questions send most PRs to the opportunity or reminder class, and what remains is a few jobs that really need looking at this week.</p>\n<p>The aim of classification is not to do fewer upgrades; it’s to do the right one at the right time. A team that meets a reminder as if it were an obligation runs for nothing; a team that takes a lock for a reminder is late. The price of both comes out of the same queue.</p>\n<p>Here I classified the signals. In part 2 of the series I’ll cover which systems to track in which layers, in part 4 how to choose the target version, and in <span data-scheduled=\"/engineering/essays/deciding-not-to-upgrade/\">part 8</span> when not upgrading is the right decision.</p>\n<p>Take the last 10 upgrade signals in your queue, sort them into mandatory, locking and opportunity, and write a response time for each.</p>",
      "content_text": "> **TL;DR:** A Dependabot PR, an EOL notice, a deprecation warning and a CVE bulletin land in the same queue but not with the same urgency. EOL and a CVE that affects you are mandatory, a dependency lock and a deprecation are locking, and features and performance are opportunity. Writing a response time for each type keeps you from rushing a reminder and from being late to a lock.\n\nMost of the PRs Dependabot opens are not obligations, they are reminders.\n\nFour kinds of signal get mixed together in the queue: Dependabot PRs, deprecation warnings, EOL announcements and CVE bulletins. Each comes from a different source for a different reason, but all of them land on the same list in the same tone. The screen looks the same; the work is not the same size.\n\nWhat is mandatory comes from somewhere else: an EOL date, a CVE, or a dependency that locks you to an old version. A team that reacts to all three the same way is either late or running for nothing.\n\n## Two Different Clocks Drop Into the Queue\n\nHow urgent a PR is doesn't say in its title; it says in which clock opened it: one is tied to an advisory, the other to the schedule in `dependabot.yml`.\n\nAccording to GitHub's documentation, when security updates are enabled, a new PR is opened when a dependency with a vulnerability is found. Version updates, on the other hand, are opened when a new version is released and run at the frequency you define in `dependabot.yml`. The first is triggered by something in the outside world, the second by a schedule you wrote.\n\nOne more detail: the `cooldown` setting delays PR creation for version updates only; it doesn't apply to security updates. So the setting you put in place to cut PR noise doesn't silence a security PR.\n\nThe practical consequence: a version update PR that arrives on a weekly schedule sits in the same queue as a PR born from an advisory, but it is not the same clock's job. You can deal with one this week and the other this quarter.\n\nBefore you open a PR, look at two things: who opened it, and which label it came with. If it's a security update, the question is no longer the version difference but whether you are affected. If it's a version update, the question is whether that version fixes anything. The answer to the second will most often be \"no, a new version came out, that's all.\"\n\n## EOL Is a Date, a CVE Is an Event\n\nEOL is known in advance. [php.net](https://www.php.net/supported-versions.php) publishes the end date of security support for each branch, and the policy is simple: two years of active support from release, then two years of security fixes only. PHP 8.2's security support ends on **31 December 2026**. That is about 9.5 weeks after this post's publication date.\n\nThe framework layer keeps its own clock too. Laravel's [12.x release notes](https://laravel.com/docs/12.x/releases) say: bug fixes are provided for 18 months, security fixes for 2 years. For Laravel 12, that means bug fixes ended on 13 August 2026 and security fixes continue until 24 February 2027. So a team running Laravel 12 on the day this post is published has already lost bug fix support, but has not yet lost security support.\n\nA CVE doesn't keep to a calendar. It can show up on a Tuesday morning, and it doesn't care which version you run.\n\nThe aftermath of EOL shouldn't be exaggerated either. Upstream support ending doesn't mean no fix will ever arrive; it means whether one arrives is no longer in your control. Ubuntu's [USN-6305-2](https://ubuntu.com/security/notices/USN-6305-2) bulletin is an example: upstream support for PHP 7.4 had ended in November 2022; on 27 February 2024, Ubuntu released fixes to its PHP packages for CVE-2023-3823 and CVE-2023-3824. `php7.4` on 20.04 got it from the standard repository; `php7.2` on 18.04 and `php7.0` on 16.04 required ESM and Ubuntu Pro.\n\nThat can be a way out. But the price is staying tied to a vendor, and leaving the question of which package the fix comes in and how fast to their schedule.\n\nThe value of an EOL date is that it is predictable. You can count the date backwards: set the line by which you want to be in production before the end date, and count back from there to staging, and from there to the test work. If I applied my recommendation below to 8.2, the line would be 30 September 2026. If you are still running 8.2 as you read this, that line has passed; this is not an accusation, it's the reason to write the plan today.\n\n## The Locking Trigger Is Invisible\n\nA locking trigger carries neither a date nor a bulletin. When a package stops supporting the old runtime, its new version becomes impossible to install, and nobody tells you.\n\nIn the PHP 7.1 case, the trigger wasn't EOL, it was a dependency lock; the details are in [The Cost of Deferring an Upgrade](/engineering/essays/the-cost-of-deferring-an-upgrade/).\n\nSince a lock has no date like an EOL, you have to measure it: of the pending package updates, how many can't be installed because of your runtime version? Every number above zero shows that a door has closed.\n\nThe lock grows quietly. Because everything keeps working on the old runtime, it raises no alarm; the first visible signal is the day the package you want to update can't be installed. On that day the type is no longer opportunity but locking, and the way out is likely to be a single piece.\n\n## Three Types, Three Response Times\n\nI sort signals into three types:\n\n- **Mandatory:** a signal that comes from outside and whose date or risk is independent of your preference (EOL, a CVE that affects you).\n- **Locking:** a signal that breaks nothing today but narrows your options tomorrow.\n- **Opportunity:** a signal where nothing breaks if you don't act, and you gain something if you do.\n\nThe response times below are my recommendation. They are not an industry standard; shift them to your own team's capacity, but write a time down. A signal with no time sits in the queue, and a signal that sits in the queue eventually comes back as \"urgent.\"\n\n| Signal | Type | Response time (my recommendation) |\n|---|---|---|\n| A CVE that affects you | Mandatory | Triage the same business day, patch within days |\n| A CVE that doesn't affect you | Opportunity | Normal cycle; the record that you're not affected is kept |\n| EOL date | Mandatory | The date goes on the calendar; in production at least 3 months before the end date |\n| Dependency lock | Locking | Goes into next quarter's plan |\n| Deprecation warning | Locking | Before the next major |\n| Feature or performance | Opportunity | Backlog; no date unless there's a measured gain |\n\nTwo rows of the table deserve a separate pause. First, the CVE: the same bulletin is mandatory if it touches a code path you use, and an opportunity if it doesn't. The urgency is set not by the bulletin's headline but by your system. Two questions are enough to settle it: am I using the affected component, and can the affected code path be reached from outside? If you answer \"yes\" to both, you are on the first row of the table; if the fix hasn't reached your version branch yet, this doesn't extend the time, it turns the job from patching into a temporary mitigation. If one of the answers is \"no,\" put that on record; the record keeps you from debating the same bulletin again a month later. Second, performance: \"the new version is faster\" is an opportunity, not an obligation. Don't open a calendar slot on that sentence without measuring.\n\nWhy is the time a quarter rather than days on the locking rows? Because a lock breaks nothing today; but if one more package drops the old runtime every quarter, the cost of the way out grows. A quarter is short enough to notice that and write it into the next planning.\n\n\n> **Tan:** Write the type and the response time where the signal lives, not in a separate doc: a label on the issue or one line in the PR description is enough. Whoever triages the queue then reads the decision from the list itself instead of opening a wiki. The \"not affected\" note lives there too, so when the same advisory comes back a month later, the answer is already attached.\n\n\n## The Limit of This Framework\n\nThis classification doesn't replace a decision matrix. The type tells you the upper bound of urgency; it doesn't tell you in which system, with what risk, in what order the work will be done.\n\nThe same CVE can be an opportunity in an internal tool and mandatory in a payment flow. What makes that distinction is how critical the system is. The decision matrix is in part 3 of the series.\n\nThe type is also not fixed. An opportunity, as it is deferred, turns into a locking one; a lock, as the EOL date approaches, turns into a mandatory one. Don't classify once and bury it in the queue; look again in every planning round.\n\n## Back to the Queue\n\nBack to the start: that Dependabot PR. Which clock opened it? An advisory, or a schedule? Is it releasing a lock, or only telling you a new version came out? Three questions send most PRs to the opportunity or reminder class, and what remains is a few jobs that really need looking at this week.\n\nThe aim of classification is not to do fewer upgrades; it's to do the right one at the right time. A team that meets a reminder as if it were an obligation runs for nothing; a team that takes a lock for a reminder is late. The price of both comes out of the same queue.\n\nHere I classified the signals. In part 2 of the series I'll cover which systems to track in which layers, in part 4 how to choose the target version, and in part 8 when not upgrading is the right decision.\n\nTake the last 10 upgrade signals in your queue, sort them into mandatory, locking and opportunity, and write a response time for each.\n\n## Sources\n\n- [Supported Versions](https://www.php.net/supported-versions.php) — PHP\n- [Laravel 12.x Release Notes](https://laravel.com/docs/12.x/releases) — Laravel\n- [Optimizing PR creation for version updates](https://docs.github.com/en/code-security/tutorials/secure-your-dependencies/optimizing-pr-creation-version-updates) — GitHub\n- [USN-6305-2: PHP vulnerabilities](https://ubuntu.com/security/notices/USN-6305-2) — Canonical",
      "date_published": "2026-10-25T00:00:00.000Z",
      "tags": [
        "dependencies",
        "decisions",
        "security",
        "production",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/integration-vs-unit-tests/",
      "url": "https://muhammetsafak.com/engineering/essays/integration-vs-unit-tests/",
      "title": "Which Test Catches the Production Bug?",
      "summary": "In practice, many production bugs originate between components, and an isolated unit test mocks exactly the connection that breaks. Unit tests shine on pure, logic-heavy cores; integration tests check glue code against a real database and HTTP layer. Spend the test budget where bugs are born, and keep mocks for external dependencies such as a payment provider.",
      "content_html": "<p>A feature with 100% unit test coverage broke in production on day one. The bug was inside no single unit; it was in the way two components talked to each other. Every unit had been tested individually, in isolation, flawlessly. The seam between the two was the one thing no test had ever seen.</p>\n<p>“Which test would have caught this bug?” is the real question behind any testing strategy.</p>\n<h2 id=\"where-real-bugs-are-born\">Where real bugs are born</h2>\n<p>Trace your production bugs back honestly and many of them land on the same address: the space <strong>between</strong> components. A payload serialized wrong, a contract that doesn’t line up, a transaction boundary drawn in the wrong place, a config difference across environments.</p>\n<p>The isolated unit test mocks out exactly the piece that breaks. A test that mocks the database can’t see a query written wrong. A test that mocks the HTTP layer can’t catch a wrong status code. A test is only as good as the fake it puts in place of the real thing.</p>\n<h2 id=\"what-unit-tests-are-for\">What unit tests are for</h2>\n<p>This is not an argument against unit tests. Unit tests have a clear value: fast feedback on complex, pure logic. A calculation, an algorithm, a state machine, a pile of edge cases — testing those with isolated, fast tests is the right move. Hundreds of scenarios in seconds.</p>\n<p>Unit tests shine when the <strong>logic</strong> is rich.</p>\n<h2 id=\"what-integration-tests-are-for\">What integration tests are for</h2>\n<p>Integration tests answer a different question: do the components actually work together? With a real database, a real HTTP layer, a real queue. Hitting an endpoint and verifying that the right row appears in the database exposes everything mocks would have hidden.</p>\n<p>A typical web application is mostly <strong>glue code</strong>: take data, validate it, save it, return it. There’s little logic and a lot of wiring in that code. Only an integration test exercises the wiring.</p>\n<h2 id=\"where-the-testing-budget-goes\">Where the testing budget goes</h2>\n<p>The classic test pyramid puts a large number of unit tests at the bottom. But for a typical web application, integration tests give the highest payoff in bug prevention — because the bugs are born in the wiring.</p>\n<p>A practical split: integration tests for the glue code; unit tests for the logic-heavy core. Piling isolated unit tests onto glue code raises <a href=\"https://muhammetsafak.com/engineering/essays/a-lean-testing-culture/\">the coverage number</a> but doesn’t protect production.</p>\n<blockquote><p><strong>Tan:</strong> When a bug escapes to production, write down which test would have caught it: unit or integration. After a few incidents, where the test budget should go stops being an argument and becomes a record. The question at the top of the piece could be the last item of every post-mortem.</p></blockquote>\n<h2 id=\"the-mock-trap\">The mock trap</h2>\n<p>The most common mistake is mocking the thing that breaks. A test that mocks the database can never tell you a query is wrong — because that test has replaced the place the query goes with a fake. A query bug like an N+1 in <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a> is only caught by a test that hits a real database.</p>\n<p>Save mocks for the external things that you don’t control and that are slow — a payment provider, say. Mocking your own database is, more often than not, cutting the test loose from reality.</p>\n<hr/>\n<p>“All tests are green” does not mean “production is safe.” If you don’t know which test prevents which bug, your test count isn’t a source of confidence, it’s a feeling.</p>\n<p>Spend your testing budget where the bugs are actually born — in the space between components.</p>",
      "content_text": "> **TL;DR:** In practice, many production bugs originate between components, and an isolated unit test mocks exactly the connection that breaks. Unit tests shine on pure, logic-heavy cores; integration tests check glue code against a real database and HTTP layer. Spend the test budget where bugs are born, and keep mocks for external dependencies such as a payment provider.\n\nA feature with 100% unit test coverage broke in production on day one. The bug was inside no single unit; it was in the way two components talked to each other. Every unit had been tested individually, in isolation, flawlessly. The seam between the two was the one thing no test had ever seen.\n\n\"Which test would have caught this bug?\" is the real question behind any testing strategy.\n\n## Where real bugs are born\n\nTrace your production bugs back honestly and many of them land on the same address: the space **between** components. A payload serialized wrong, a contract that doesn't line up, a transaction boundary drawn in the wrong place, a config difference across environments.\n\nThe isolated unit test mocks out exactly the piece that breaks. A test that mocks the database can't see a query written wrong. A test that mocks the HTTP layer can't catch a wrong status code. A test is only as good as the fake it puts in place of the real thing.\n\n## What unit tests are for\n\nThis is not an argument against unit tests. Unit tests have a clear value: fast feedback on complex, pure logic. A calculation, an algorithm, a state machine, a pile of edge cases — testing those with isolated, fast tests is the right move. Hundreds of scenarios in seconds.\n\nUnit tests shine when the **logic** is rich.\n\n## What integration tests are for\n\nIntegration tests answer a different question: do the components actually work together? With a real database, a real HTTP layer, a real queue. Hitting an endpoint and verifying that the right row appears in the database exposes everything mocks would have hidden.\n\nA typical web application is mostly **glue code**: take data, validate it, save it, return it. There's little logic and a lot of wiring in that code. Only an integration test exercises the wiring.\n\n## Where the testing budget goes\n\nThe classic test pyramid puts a large number of unit tests at the bottom. But for a typical web application, integration tests give the highest payoff in bug prevention — because the bugs are born in the wiring.\n\nA practical split: integration tests for the glue code; unit tests for the logic-heavy core. Piling isolated unit tests onto glue code raises [the coverage number](/engineering/essays/a-lean-testing-culture/) but doesn't protect production.\n\n\n> **Tan:** When a bug escapes to production, write down which test would have caught it: unit or integration. After a few incidents, where the test budget should go stops being an argument and becomes a record. The question at the top of the piece could be the last item of every post-mortem.\n\n\n## The mock trap\n\nThe most common mistake is mocking the thing that breaks. A test that mocks the database can never tell you a query is wrong — because that test has replaced the place the query goes with a fake. A query bug like an N+1 in [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/) is only caught by a test that hits a real database.\n\nSave mocks for the external things that you don't control and that are slow — a payment provider, say. Mocking your own database is, more often than not, cutting the test loose from reality.\n\n---\n\n\"All tests are green\" does not mean \"production is safe.\" If you don't know which test prevents which bug, your test count isn't a source of confidence, it's a feeling.\n\nSpend your testing budget where the bugs are actually born — in the space between components.",
      "date_published": "2026-10-24T00:00:00.000Z",
      "tags": [
        "testing",
        "quality",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/",
      "url": "https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/",
      "title": "The Cost of Deferring an Upgrade",
      "summary": "Deferring an upgrade is not avoiding risk; it is accumulating risk where no one can see it. As packages drop support for the old runtime one by one, a dependency lock gets set quietly, and a job of 1–2 days turns into dozens of breaking changes to fix at once and a bug queue that stretches over months. A deferral is only a decision once its date and its reason are written down.",
      "content_html": "<p>When I proposed moving from PHP 7.1 to a stable 8.2, the answer was short: “It works, so why bother?” The answer was right — nothing was broken that day. What had started to break was invisible: packages were dropping support for old PHP one by one, and the application was getting locked to 7.1.</p>\n<p>“It works” describes today. The bill is issued by the days that follow.</p>\n<p>The objection isn’t illogical, so I don’t wave it away. Spending time on something that isn’t broken looks like gaining nothing. You can’t refute a sentence that is right by arguing with the sentence; you have to come with a number. What follows is the accounting of what that sentence cost me: by which mechanism, in which line items, and how much of it I was able to measure.</p>\n<h2 id=\"how-the-lock-gets-set\">How the Lock Gets Set</h2>\n<p>The lock wasn’t set in a single day; with every package update, one more door closed.</p>\n<p>The mechanism is ordinary. A package drops support for the old runtime in its new version. Since the runtime hasn’t been upgraded, that version can’t be installed, and you stay on the old one. The same thing happens with the next package, then the one after. None of them raises an alarm on its own: the old version keeps working.</p>\n<p>At some point no package is left that can be updated. I call this a <strong>dependency lock</strong>: the application is tied to the runtime, the packages to the application, and all of it together to 7.1. The way out is a single piece. I couldn’t move any package forward without upgrading the runtime; and without moving the packages forward, I couldn’t see what the upgrade would cost.</p>\n<p>That’s why the lock is set unnoticed. Each door that closes is, on its own, a detail that can be deferred; no single package update looks big enough to make you say “we have to do the upgrade today.” Deferring the decision is reasonable every single time. The sum of reasonable decisions is being backed into a corner.</p>\n<p>The worst thing about the lock is that it is silent. No error message says “another door closed today.” You notice it only on the day you try to update a package, while reading why the update won’t install.</p>\n<p>The sign to look for in your own system is simple. Of the pending package updates, how many can’t be installed because of the runtime version? Every number above zero shows that a door has closed.</p>\n<h2 id=\"the-only-number-i-have\">The Only Number I Have</h2>\n<p>On the day I proposed it, the job was a 1–2 day upgrade. While the lock was being set, each package update took a few hours. Both looked like small jobs, and that’s why deferring was easy.</p>\n<p>A small job is a good candidate for deferral; “let’s finish the urgent thing first” fits into every calendar.</p>\n<p>Once deferred, the job didn’t just grow; because it had piled up, it became a single piece. I had to skip versions: not from 7.1 to 8.2 step by step, but passing everything in between in one go. Dozens of breaking changes and deprecated methods lay ahead of me, and all of them had to be solved at the same time. A debt that could have been paid in installments turned into a single collection.</p>\n<p>What the number really taught me isn’t the amount itself but the change in the kind of work. A few hours of package updates were piecemeal jobs that could be done in any order, on any day. Dozens of breaking changes are one indivisible job that has to be finished once started. Deferring didn’t only make the job bigger; it took away its flexibility.</p>\n<p>This is the only number I have: a 1–2 day job, plus a few hours per package update. I have no measurement to set next to it for the total cost of deferring. I won’t set one, either; writing down a number I didn’t measure would be a worse argument than “it works, doesn’t it.”</p>\n<p>Even so, this one number is enough to start a conversation. Against “it works, doesn’t it,” you can go not with “we’re gaining nothing,” but with “1–2 days now, dozens of changes in one go later.” To explain the difference between the two to a manager, a measurement isn’t essential; the direction of the comparison is enough.</p>\n<p>How to produce the number is in part 7 of the series; which upgrade comes first is in part 3. Here I’ll say only this: if I could have put this comparison on the table that day, “it works” alone wouldn’t have been enough of an answer.</p>\n<h2 id=\"the-real-line-item-on-the-bill\">The Real Line Item on the Bill</h2>\n<p>We cleaned up the breaking changes; what we didn’t expect was the bugs that came after.</p>\n<p>Breaking changes have a good property: the error message points to them. You draw up the list, close them one by one, and it’s over. This item is long but known: you can roughly estimate its size, place it on the calendar, and tell your manager.</p>\n<p>The bugs weren’t like that. Some of them showed up in only a single case — a path that rarely gets triggered, a particular piece of data, a particular order. For a bug like that you first have to see it, then reproduce it, then find its cause. Each one is a separate investigation. Their fixes spread over months. One bug would close, and another would show up in a different case.</p>\n<p>For planning, the two have to be written separately. Breaking changes are a predictable item; bugs are not. If you build the budget only for the first, the second lives outside the budget and inside the calendar.</p>\n<p>That’s where the real cost is: the <strong>long tail</strong>. The price of the batch migration fits the calendar; the price of the tail doesn’t. On top of that, because I was carrying dozens of changes together, the source of every bug was one of dozens of candidates; telling which bug came from which change created a job of its own.</p>\n<h2 id=\"it-works-describes-today\">“It Works” Describes Today</h2>\n<p>Saying “there’s technical debt” isn’t enough against the “it works, doesn’t it” objection; the person across the table hears it as an opinion. To answer in business language, you have to break the risk into line items. Every deferred upgrade accumulates four:</p>\n<ul>\n<li><strong>End of support:</strong> once the runtime or framework is no longer maintained, no new fixes arrive. A set day on the calendar, a known date.</li>\n<li><strong>Time exposed to CVEs:</strong> for every CVE announced after the day support ends, no official patch arrives; unless your distribution or a paid extended support patches it, the hole stays in the system until you upgrade. The counter starts the day support ends and stops on the day of the upgrade.</li>\n<li><strong>Dependency lock:</strong> as packages are pinned to old versions, your update options narrow. Once the lock is set, the only way out is to move everything together.</li>\n<li><strong>Growing version gap:</strong> as the number of versions in between grows, so does the number of breaking changes and deprecated methods to solve in one go. In my case, that was dozens of items.</li>\n</ul>\n<p>None of these produces an error today, and none shows on the monitoring dashboard; all of them will be paid tomorrow. For a manager the difference is this too: asking for budget for something broken is easy, explaining why something that isn’t broken will break is hard. That’s why naming the items works, because each one can be tied to a date, a counter, or a number.</p>\n<p>The summary of the four items: <strong>“it works” describes today; risk is tomorrow’s balance-sheet item.</strong> The cost of upgrading is known, and you schedule the payment. The cost of deferring is unknown, and you don’t get to pick when it is collected.</p>\n<blockquote><p><strong>Tan:</strong> The post makes the cost of waiting plain. What bothers me is that the burden of proof always sits with whoever proposes the upgrade. People ask for a reason to upgrade; almost nobody asks for a reason to wait. If both questions were on the table, would “it works” still win so easily?</p></blockquote>\n<h2 id=\"when-do-you-let-it-go\">When Do You Let It Go?</h2>\n<p>Not upgrading can also be a legitimate decision; in which cases, I’m leaving to <span data-scheduled=\"/engineering/essays/deciding-not-to-upgrade/\">part 8</span> of the series. My objection here isn’t to deferring, but to the deferral not being written down as a decision.</p>\n<p>Deferring can be a conscious decision; but a decision that isn’t written down comes back one day as a surprise. A deferral with its date and reason written down is risk management; one without is just forgetting.</p>\n<p>There is one thing you can do today: look up the end-of-support dates of the runtime and framework versions you use, and write them down somewhere. Even if the system has no inventory, two lines are enough: what’s running, and when its support ends. The next time someone asks “why?”, you’ll at least have a date in hand. If you also write next to the date how many versions behind the system will be by then, the question stops being “does it work” and becomes “when will we pay”; and the conversation starts there.</p>\n<p>Ask yourself: if upgrading this system today were a 1–2 day job, would you do it? If the answer is yes, there’s nothing to gain by waiting; the job only grows.</p>\n<p>The series continues from here: in part 1, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-triggers/\">the situations that trigger an upgrade</a>; in part 2, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-inventory/\">the inventory and layers</a> for seeing what will be upgraded; in part 3, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-decision-matrix/\">the decision matrix</a>; and up to part 8, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-target-version/\">the target version</a>, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-prerequisites/\">prerequisites</a>, <a href=\"https://muhammetsafak.com/engineering/notes/upgrade-rollout-one-way-doors/\">rollout</a>, and <span data-scheduled=\"/engineering/essays/upgrade-organization/\">organization</span>.</p>\n<p>When you defer an upgrade, you don’t close the risk; you write the bill to the next day.</p>",
      "content_text": "> **TL;DR:** Deferring an upgrade is not avoiding risk; it is accumulating risk where no one can see it. As packages drop support for the old runtime one by one, a dependency lock gets set quietly, and a job of 1–2 days turns into dozens of breaking changes to fix at once and a bug queue that stretches over months. A deferral is only a decision once its date and its reason are written down.\n\nWhen I proposed moving from PHP 7.1 to a stable 8.2, the answer was short: \"It works, so why bother?\" The answer was right — nothing was broken that day. What had started to break was invisible: packages were dropping support for old PHP one by one, and the application was getting locked to 7.1.\n\n\"It works\" describes today. The bill is issued by the days that follow.\n\nThe objection isn't illogical, so I don't wave it away. Spending time on something that isn't broken looks like gaining nothing. You can't refute a sentence that is right by arguing with the sentence; you have to come with a number. What follows is the accounting of what that sentence cost me: by which mechanism, in which line items, and how much of it I was able to measure.\n\n## How the Lock Gets Set\n\nThe lock wasn't set in a single day; with every package update, one more door closed.\n\nThe mechanism is ordinary. A package drops support for the old runtime in its new version. Since the runtime hasn't been upgraded, that version can't be installed, and you stay on the old one. The same thing happens with the next package, then the one after. None of them raises an alarm on its own: the old version keeps working.\n\nAt some point no package is left that can be updated. I call this a **dependency lock**: the application is tied to the runtime, the packages to the application, and all of it together to 7.1. The way out is a single piece. I couldn't move any package forward without upgrading the runtime; and without moving the packages forward, I couldn't see what the upgrade would cost.\n\nThat's why the lock is set unnoticed. Each door that closes is, on its own, a detail that can be deferred; no single package update looks big enough to make you say \"we have to do the upgrade today.\" Deferring the decision is reasonable every single time. The sum of reasonable decisions is being backed into a corner.\n\nThe worst thing about the lock is that it is silent. No error message says \"another door closed today.\" You notice it only on the day you try to update a package, while reading why the update won't install.\n\nThe sign to look for in your own system is simple. Of the pending package updates, how many can't be installed because of the runtime version? Every number above zero shows that a door has closed.\n\n## The Only Number I Have\n\nOn the day I proposed it, the job was a 1–2 day upgrade. While the lock was being set, each package update took a few hours. Both looked like small jobs, and that's why deferring was easy.\n\nA small job is a good candidate for deferral; \"let's finish the urgent thing first\" fits into every calendar.\n\nOnce deferred, the job didn't just grow; because it had piled up, it became a single piece. I had to skip versions: not from 7.1 to 8.2 step by step, but passing everything in between in one go. Dozens of breaking changes and deprecated methods lay ahead of me, and all of them had to be solved at the same time. A debt that could have been paid in installments turned into a single collection.\n\nWhat the number really taught me isn't the amount itself but the change in the kind of work. A few hours of package updates were piecemeal jobs that could be done in any order, on any day. Dozens of breaking changes are one indivisible job that has to be finished once started. Deferring didn't only make the job bigger; it took away its flexibility.\n\nThis is the only number I have: a 1–2 day job, plus a few hours per package update. I have no measurement to set next to it for the total cost of deferring. I won't set one, either; writing down a number I didn't measure would be a worse argument than \"it works, doesn't it.\"\n\nEven so, this one number is enough to start a conversation. Against \"it works, doesn't it,\" you can go not with \"we're gaining nothing,\" but with \"1–2 days now, dozens of changes in one go later.\" To explain the difference between the two to a manager, a measurement isn't essential; the direction of the comparison is enough.\n\nHow to produce the number is in part 7 of the series; which upgrade comes first is in part 3. Here I'll say only this: if I could have put this comparison on the table that day, \"it works\" alone wouldn't have been enough of an answer.\n\n## The Real Line Item on the Bill\n\nWe cleaned up the breaking changes; what we didn't expect was the bugs that came after.\n\nBreaking changes have a good property: the error message points to them. You draw up the list, close them one by one, and it's over. This item is long but known: you can roughly estimate its size, place it on the calendar, and tell your manager.\n\nThe bugs weren't like that. Some of them showed up in only a single case — a path that rarely gets triggered, a particular piece of data, a particular order. For a bug like that you first have to see it, then reproduce it, then find its cause. Each one is a separate investigation. Their fixes spread over months. One bug would close, and another would show up in a different case.\n\nFor planning, the two have to be written separately. Breaking changes are a predictable item; bugs are not. If you build the budget only for the first, the second lives outside the budget and inside the calendar.\n\nThat's where the real cost is: the **long tail**. The price of the batch migration fits the calendar; the price of the tail doesn't. On top of that, because I was carrying dozens of changes together, the source of every bug was one of dozens of candidates; telling which bug came from which change created a job of its own.\n\n## \"It Works\" Describes Today\n\nSaying \"there's technical debt\" isn't enough against the \"it works, doesn't it\" objection; the person across the table hears it as an opinion. To answer in business language, you have to break the risk into line items. Every deferred upgrade accumulates four:\n\n- **End of support:** once the runtime or framework is no longer maintained, no new fixes arrive. A set day on the calendar, a known date.\n- **Time exposed to CVEs:** for every CVE announced after the day support ends, no official patch arrives; unless your distribution or a paid extended support patches it, the hole stays in the system until you upgrade. The counter starts the day support ends and stops on the day of the upgrade.\n- **Dependency lock:** as packages are pinned to old versions, your update options narrow. Once the lock is set, the only way out is to move everything together.\n- **Growing version gap:** as the number of versions in between grows, so does the number of breaking changes and deprecated methods to solve in one go. In my case, that was dozens of items.\n\nNone of these produces an error today, and none shows on the monitoring dashboard; all of them will be paid tomorrow. For a manager the difference is this too: asking for budget for something broken is easy, explaining why something that isn't broken will break is hard. That's why naming the items works, because each one can be tied to a date, a counter, or a number.\n\nThe summary of the four items: **\"it works\" describes today; risk is tomorrow's balance-sheet item.** The cost of upgrading is known, and you schedule the payment. The cost of deferring is unknown, and you don't get to pick when it is collected.\n\n\n> **Tan:** The post makes the cost of waiting plain. What bothers me is that the burden of proof always sits with whoever proposes the upgrade. People ask for a reason to upgrade; almost nobody asks for a reason to wait. If both questions were on the table, would “it works” still win so easily?\n\n\n## When Do You Let It Go?\n\nNot upgrading can also be a legitimate decision; in which cases, I'm leaving to part 8 of the series. My objection here isn't to deferring, but to the deferral not being written down as a decision.\n\nDeferring can be a conscious decision; but a decision that isn't written down comes back one day as a surprise. A deferral with its date and reason written down is risk management; one without is just forgetting.\n\nThere is one thing you can do today: look up the end-of-support dates of the runtime and framework versions you use, and write them down somewhere. Even if the system has no inventory, two lines are enough: what's running, and when its support ends. The next time someone asks \"why?\", you'll at least have a date in hand. If you also write next to the date how many versions behind the system will be by then, the question stops being \"does it work\" and becomes \"when will we pay\"; and the conversation starts there.\n\nAsk yourself: if upgrading this system today were a 1–2 day job, would you do it? If the answer is yes, there's nothing to gain by waiting; the job only grows.\n\nThe series continues from here: in part 1, [the situations that trigger an upgrade](/engineering/notes/upgrade-triggers/); in part 2, [the inventory and layers](/engineering/notes/upgrade-inventory/) for seeing what will be upgraded; in part 3, [the decision matrix](/engineering/notes/upgrade-decision-matrix/); and up to part 8, [the target version](/engineering/notes/upgrade-target-version/), [prerequisites](/engineering/notes/upgrade-prerequisites/), [rollout](/engineering/notes/upgrade-rollout-one-way-doors/), and organization.\n\nWhen you defer an upgrade, you don't close the risk; you write the bill to the next day.\n\n## Frequently asked\n\n### It works, so why bother?\n\n\"It works\" describes today; risk is tomorrow's balance-sheet item. Every deferred upgrade accumulates four line items: end of support, time exposed to CVEs, a dependency lock, and a growing version gap. None of them produces an error today, and all of them are paid tomorrow. The cost of upgrading is known and you schedule the payment; the cost of deferring is unknown and you don't get to pick when it is collected.\n\n### Of the pending package updates, how many can't be installed because of the runtime version?\n\nThis number is the sign that shows whether a dependency lock has been set. Packages drop support for the old runtime one by one; none of them raises an alarm, and the old version keeps working. Every number above zero means a door has closed. At some point no package is left that can be updated, and the only way out is to move everything together.",
      "date_published": "2026-10-18T00:00:00.000Z",
      "tags": [
        "technical-debt",
        "decisions",
        "dependencies",
        "opinion",
        "Upgrading in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/a-lean-testing-culture/",
      "url": "https://muhammetsafak.com/engineering/essays/a-lean-testing-culture/",
      "title": "Chasing 100% Coverage With Tests That Do Nothing",
      "summary": "Coverage measures only that a line ran, not that it was verified; once it becomes a target, people write the cheapest tests that raise the number and catch no bugs. A test is worth the bugs it catches: test the behavior that matters and let coverage arrive as a by-product. Spend the test budget on complex logic, code that handles money and places that have failed before.",
      "content_html": "<p>I saw a pull request: forty new tests, all serving a single purpose — pushing coverage to 100%. Most of them called a getter and verified that the value just set came back. Coverage turned green. The number of bugs those forty tests would catch: zero.</p>\n<p>Test coverage is a useful number — until you turn it into a target.</p>\n<h2 id=\"what-coverage-measures-and-what-it-doesnt\">What coverage measures, and what it doesn’t</h2>\n<p>Coverage measures one thing: which lines of code <strong>run</strong> while the tests execute. What it doesn’t measure matters far more: whether those lines are actually <strong>verified</strong>.</p>\n<p>A line counts as “covered” even by a test with no meaningful <code>assert</code>. The code runs, the test is green, but nobody has checked whether the code behaves correctly. Coverage can’t see the difference between code that runs and code that’s verified.</p>\n<h2 id=\"the-wrong-metric-rewards-the-wrong-test\">The wrong metric rewards the wrong test</h2>\n<p>Once coverage becomes a target, human behavior is predictable: people write the tests that raise the number by the cheapest route.</p>\n<ul>\n<li>Getter/setter tests — testing code that has no logic.</li>\n<li>Tests that verify a mock was called — an interaction, not a real result.</li>\n<li>Tests whose <code>assert</code> is meaningless, which only say “it didn’t blow up”.</li>\n</ul>\n<p>These raise the coverage number and catch no bugs. Worse: a green 100% gives the team false confidence. Code that’s assumed to be tested has merely been executed.</p>\n<h2 id=\"the-measure-of-a-good-test\">The measure of a good test</h2>\n<p>A test’s value lies not in the line it covers but in the bug it catches. A simple check: deliberately break the logic of the code — turn a <code>+</code> into a <code>-</code>, invert a condition. A good test goes red. If it doesn’t, that test isn’t verifying anything.</p>\n<p>The systematic form of this idea is mutation testing: the tool breaks the code in small ways and measures whether your tests catch it. Coverage says “did the line run”; mutation testing says “was the line actually tested”.</p>\n<h2 id=\"coverage-is-a-byproduct\">Coverage is a byproduct</h2>\n<p>The right order is the reverse: test the behavior that matters first, and let coverage rise as a <strong>byproduct</strong>. Chase the number and you write tests that do nothing; chase the behavior and coverage comes anyway — and the coverage you get is real.</p>\n<p>100% is not a target. A critical path that’s never tested can exist even in a 100% codebase; conversely, a system with 75% coverage may be solidly testing every risky path.</p>\n<h2 id=\"where-to-spend-the-testing-budget\">Where to spend the testing budget</h2>\n<p>Writing tests is also writing code; it has a limited budget. Spend that budget according to risk:</p>\n<ul>\n<li>Complex logic, code that handles money, calculations.</li>\n<li>Edge cases — boundary values, empty input, concurrency.</li>\n<li>Places that have broken before — if a bug came out of there once, it will again.</li>\n</ul>\n<p>Testing trivial, logicless code wastes the budget. The “the test setup is longer than the test itself” sign I mentioned in <a href=\"https://muhammetsafak.com/engineering/essays/signals-of-an-over-complex-system/\">signals that a system has grown too complex</a> connects here too: if a test is very hard to write, the problem isn’t the test, it’s that the code under test is too tightly coupled.</p>\n<hr/>\n<p>A coverage percentage is not a source of confidence; it’s only an observation. Confidence comes from the bugs your tests catch — not the number they chase.</p>\n<p>Aim not for the number, but for the test that goes red when the code is wrong.</p>",
      "content_text": "> **TL;DR:** Coverage measures only that a line ran, not that it was verified; once it becomes a target, people write the cheapest tests that raise the number and catch no bugs. A test is worth the bugs it catches: test the behavior that matters and let coverage arrive as a by-product. Spend the test budget on complex logic, code that handles money and places that have failed before.\n\nI saw a pull request: forty new tests, all serving a single purpose — pushing coverage to 100%. Most of them called a getter and verified that the value just set came back. Coverage turned green. The number of bugs those forty tests would catch: zero.\n\nTest coverage is a useful number — until you turn it into a target.\n\n## What coverage measures, and what it doesn't\n\nCoverage measures one thing: which lines of code **run** while the tests execute. What it doesn't measure matters far more: whether those lines are actually **verified**.\n\nA line counts as \"covered\" even by a test with no meaningful `assert`. The code runs, the test is green, but nobody has checked whether the code behaves correctly. Coverage can't see the difference between code that runs and code that's verified.\n\n## The wrong metric rewards the wrong test\n\nOnce coverage becomes a target, human behavior is predictable: people write the tests that raise the number by the cheapest route.\n\n- Getter/setter tests — testing code that has no logic.\n- Tests that verify a mock was called — an interaction, not a real result.\n- Tests whose `assert` is meaningless, which only say \"it didn't blow up\".\n\nThese raise the coverage number and catch no bugs. Worse: a green 100% gives the team false confidence. Code that's assumed to be tested has merely been executed.\n\n## The measure of a good test\n\nA test's value lies not in the line it covers but in the bug it catches. A simple check: deliberately break the logic of the code — turn a `+` into a `-`, invert a condition. A good test goes red. If it doesn't, that test isn't verifying anything.\n\nThe systematic form of this idea is mutation testing: the tool breaks the code in small ways and measures whether your tests catch it. Coverage says \"did the line run\"; mutation testing says \"was the line actually tested\".\n\n## Coverage is a byproduct\n\nThe right order is the reverse: test the behavior that matters first, and let coverage rise as a **byproduct**. Chase the number and you write tests that do nothing; chase the behavior and coverage comes anyway — and the coverage you get is real.\n\n100% is not a target. A critical path that's never tested can exist even in a 100% codebase; conversely, a system with 75% coverage may be solidly testing every risky path.\n\n## Where to spend the testing budget\n\nWriting tests is also writing code; it has a limited budget. Spend that budget according to risk:\n\n- Complex logic, code that handles money, calculations.\n- Edge cases — boundary values, empty input, concurrency.\n- Places that have broken before — if a bug came out of there once, it will again.\n\nTesting trivial, logicless code wastes the budget. The \"the test setup is longer than the test itself\" sign I mentioned in [signals that a system has grown too complex](/engineering/essays/signals-of-an-over-complex-system/) connects here too: if a test is very hard to write, the problem isn't the test, it's that the code under test is too tightly coupled.\n\n---\n\nA coverage percentage is not a source of confidence; it's only an observation. Confidence comes from the bugs your tests catch — not the number they chase.\n\nAim not for the number, but for the test that goes red when the code is wrong.",
      "date_published": "2026-10-17T00:00:00.000Z",
      "tags": [
        "testing",
        "quality",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/third-party-package-dependency/",
      "url": "https://muhammetsafak.com/engineering/essays/third-party-package-dependency/",
      "title": "The Cost of Installing a Package for Everything",
      "summary": "Installing a package for a small function puts someone else's code into your codebase, running with your own privileges: security surface, maintenance and upgrade friction add up to a bill that does not end at installation. A package wins on hard, security-critical work such as cryptography, HTTP clients and database drivers; for small, stable work you understand, writing those few lines yourself is cheaper.",
      "content_html": "<p>One project’s <code>composer.lock</code> had 180 packages. The ones used directly, counted by hand, were twelve. The rest — over a hundred packages — were mostly dependencies dragged in by packages installed for a small function.</p>\n<p>Typing <code>composer require</code> feels free. It is not. Every dependency is a door into your codebase, opening onto someone else’s code — and that door never fully closes again.</p>\n<h2 id=\"every-dependency-is-a-door\">Every dependency is a door</h2>\n<p>When you install a package, that package’s code runs on your server, with your application’s privileges. It can reach your database, see your file system, read your environment variables.</p>\n<p>This does not mean the package is malicious — but if it gets compromised one day, your application gets compromised too. This is what a supply-chain attack is: the weak link is not the code you wrote, it is the code you trust. If you trust hundreds of packages, that means there are hundreds of teams you have to trust.</p>\n<h2 id=\"the-line-items-on-the-bill\">The line items on the bill</h2>\n<p>A dependency’s cost does not end at installation:</p>\n<ul>\n<li><strong>Security surface.</strong> Every package is a piece of code you have not audited. With transitive dependencies, no one fully knows what you are actually trusting.</li>\n<li><strong>Maintenance.</strong> A package gets abandoned, breaks on a new PHP version, conflicts with another package. Its problem is now your problem.</li>\n<li><strong><a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-deferring-an-upgrade/\">Upgrade friction</a>.</strong> When you want to upgrade the framework, you are only as fast as your oldest, least-maintained dependency.</li>\n</ul>\n<p>These line items are paid for a small package just as they are for a large one.</p>\n<h2 id=\"small-job-big-door\">Small job, big door</h2>\n<p>The real issue is the asymmetry. A few lines of helper code that generate a slug, format a date — installing a package for these opens a wide door for a small gain. The gain is a few lines of code; the cost is the entire bill above.</p>\n<p>There is a famous example: in the JavaScript world, an eleven-line package that left-pads a string was unpublished one day, and the builds of thousands of projects collapsed. For eleven lines, all of them had tied themselves to a door they never audited.</p>\n<h2 id=\"when-to-use-a-package-when-to-write-it-yourself\">When to use a package, when to write it yourself</h2>\n<p>The rule is not ideological, it is economic:</p>\n<ul>\n<li><strong>Use a package:</strong> for hard, well-tested, security-critical work. Cryptography, HTTP clients, database drivers, the framework itself. <strong>Never</strong> write your own crypto code — this is where the package wins, no argument.</li>\n<li><strong>Write it yourself:</strong> for small, stable work you understand well. A few lines of helper code are cheaper than inheriting an entire dependency tree.</li>\n</ul>\n<p>The measure is this: is the problem the package solves bigger than the bill the package brings? If it is bigger, install it. If not, write those few lines and own them.</p>\n<h2 id=\"choosing-a-dependency\">Choosing a dependency</h2>\n<p>If you have decided to install a package, look at which one you pick: is it actively maintained, when was its last release, how many transitive dependencies does it drag in, is its license suitable, how broad is its community? Choosing a dependency follows the same logic as the innovation token in the <a href=\"https://muhammetsafak.com/engineering/essays/why-boring-architecture/\">boring architecture</a> piece: pick the one that is mature, predictable, and will not be abandoned.</p>\n<hr/>\n<p>Adding a dependency looks like a way to avoid writing code. In reality it is getting someone else to write the code while you keep the responsibility.</p>\n<p>Before opening an entire door for a small job, ask: is writing those few lines really more expensive?</p>",
      "content_text": "> **TL;DR:** Installing a package for a small function puts someone else's code into your codebase, running with your own privileges: security surface, maintenance and upgrade friction add up to a bill that does not end at installation. A package wins on hard, security-critical work such as cryptography, HTTP clients and database drivers; for small, stable work you understand, writing those few lines yourself is cheaper.\n\nOne project's `composer.lock` had 180 packages. The ones used directly, counted by hand, were twelve. The rest — over a hundred packages — were mostly dependencies dragged in by packages installed for a small function.\n\nTyping `composer require` feels free. It is not. Every dependency is a door into your codebase, opening onto someone else's code — and that door never fully closes again.\n\n## Every dependency is a door\n\nWhen you install a package, that package's code runs on your server, with your application's privileges. It can reach your database, see your file system, read your environment variables.\n\nThis does not mean the package is malicious — but if it gets compromised one day, your application gets compromised too. This is what a supply-chain attack is: the weak link is not the code you wrote, it is the code you trust. If you trust hundreds of packages, that means there are hundreds of teams you have to trust.\n\n## The line items on the bill\n\nA dependency's cost does not end at installation:\n\n- **Security surface.** Every package is a piece of code you have not audited. With transitive dependencies, no one fully knows what you are actually trusting.\n- **Maintenance.** A package gets abandoned, breaks on a new PHP version, conflicts with another package. Its problem is now your problem.\n- **[Upgrade friction](/engineering/essays/the-cost-of-deferring-an-upgrade/).** When you want to upgrade the framework, you are only as fast as your oldest, least-maintained dependency.\n\nThese line items are paid for a small package just as they are for a large one.\n\n## Small job, big door\n\nThe real issue is the asymmetry. A few lines of helper code that generate a slug, format a date — installing a package for these opens a wide door for a small gain. The gain is a few lines of code; the cost is the entire bill above.\n\nThere is a famous example: in the JavaScript world, an eleven-line package that left-pads a string was unpublished one day, and the builds of thousands of projects collapsed. For eleven lines, all of them had tied themselves to a door they never audited.\n\n## When to use a package, when to write it yourself\n\nThe rule is not ideological, it is economic:\n\n- **Use a package:** for hard, well-tested, security-critical work. Cryptography, HTTP clients, database drivers, the framework itself. **Never** write your own crypto code — this is where the package wins, no argument.\n- **Write it yourself:** for small, stable work you understand well. A few lines of helper code are cheaper than inheriting an entire dependency tree.\n\nThe measure is this: is the problem the package solves bigger than the bill the package brings? If it is bigger, install it. If not, write those few lines and own them.\n\n## Choosing a dependency\n\nIf you have decided to install a package, look at which one you pick: is it actively maintained, when was its last release, how many transitive dependencies does it drag in, is its license suitable, how broad is its community? Choosing a dependency follows the same logic as the innovation token in the [boring architecture](/engineering/essays/why-boring-architecture/) piece: pick the one that is mature, predictable, and will not be abandoned.\n\n---\n\nAdding a dependency looks like a way to avoid writing code. In reality it is getting someone else to write the code while you keep the responsibility.\n\nBefore opening an entire door for a small job, ask: is writing those few lines really more expensive?\n\n## Sources\n\n- [kik, left-pad, and npm](https://blog.npmjs.org/post/141577284765/kik-left-pad-and-npm) — npm",
      "date_published": "2026-10-10T00:00:00.000Z",
      "tags": [
        "dependencies",
        "security",
        "simplicity",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/when-is-cqrs-necessary/",
      "url": "https://muhammetsafak.com/engineering/notes/when-is-cqrs-necessary/",
      "title": "CQRS: When You Need It, When It's Dead Weight",
      "summary": "CQRS separates the write model from the read model; that does not necessarily mean two databases or a read replica. It brings clarity in complex domains where the shape of writes and reads really diverges, and in plain CRUD it adds only a second model to keep in sync and twice the code. Lightweight CQRS starts with a separate query class.",
      "content_html": "<p>I once saw a codebase where a plain CRUD application claimed “we implemented CQRS.” A single “create user” operation had a Command, a CommandHandler, a separate read model, and a projection. All that ceremony ended in one line of <code>INSERT</code>.</p>\n<p>CQRS buys real clarity in some systems. In this application, the only thing it bought was twice the code.</p>\n<h2 id=\"what-cqrs-is-briefly\">What CQRS is, briefly</h2>\n<p>CQRS — Command Query Responsibility Segregation — rests on a single idea: separate the <strong>write model</strong> from the <strong>read model</strong>.</p>\n<p>In the classic approach a single model is both written and read — the same <code>Order</code> class both creates an order and renders it on screen. CQRS splits this in two: a write side that is a normalized model enforcing the rules; a read side that is a denormalized model shaped to the screen.</p>\n<p>Note: this does not necessarily mean two databases. Most of the time it means two <strong>models</strong> — they can live in the same database.</p>\n<h2 id=\"dont-confuse-it-with-a-read-replica\">Don’t confuse it with a read replica</h2>\n<p>A common confusion: people think CQRS and a read replica are the same thing. They are not.</p>\n<ul>\n<li>A <strong>read replica</strong> (<a href=\"https://muhammetsafak.com/engineering/notes/read-write-splitting/\">read/write splitting</a>) is an infrastructure decision: same model, different server. To scale read load.</li>\n<li><strong>CQRS</strong> is a modeling decision: different model, same or different location. Because the <strong>shape</strong> of reads and writes has diverged.</li>\n</ul>\n<p>You can use either one without the other. You can have a read replica but a single model; or do CQRS but on a single server. For a concrete case of that choice — heavy reporting reads against a few writes, replica first, outbox-fed projections only if query shapes diverge — see the Just Ask answer <a href=\"https://muhammetsafak.com/just-ask/when-to-apply-cqrs-and-syncing-read-and-write-models/\">When should I apply CQRS, and how do I sync the read and write models?</a>.</p>\n<h2 id=\"what-cqrs-buys-you\">What CQRS buys you</h2>\n<p>CQRS adds value when the write model and the read model <strong>genuinely</strong> diverge. That happens in complex domains: the shape you write drifts away from the shape you read.</p>\n<p>The write side is a normalized model that enforces invariants and carries business rules. The read side is a model flattened to the needs of the screens, precomputed, fast to query. Forcing them into a single model makes both mediocre.</p>\n<h2 id=\"dead-weight-in-plain-crud\">Dead weight in plain CRUD</h2>\n<p>Here’s the problem: in a plain CRUD application the write model and the read model are <strong>already the same</strong> — both are that row itself. Applying CQRS there is modeling a distinction that doesn’t exist.</p>\n<p>The result: two models, two structures that must be kept in sync, twice the code — and zero gain in return. This is <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-just-in-case-code/\">speculative generality</a> at the scale of a pattern: paying today for a complexity that doesn’t exist today.</p>\n<h2 id=\"lightweight-cqrs\">Lightweight CQRS</h2>\n<p>To “do” CQRS you don’t need event sourcing, separate databases, or projection infrastructure. Those are the heaviest form of CQRS, not its mandatory form.</p>\n<p>A lightweight start: leave the write side on plain Eloquent models, and for the read side write a separate query class that returns a DTO shaped to the screen. The write and read paths are separated in code — which is the essence of CQRS already. Move to the heavy infrastructure only when you actually need it.</p>\n<blockquote><p><strong>Tan:</strong> If the read model is updated through a separate flow after the write, a user may not see what they just saved. Before settling on CQRS, ask whether the product side can accept that delay. The lightweight form often takes this question off the table.</p></blockquote>\n<h2 id=\"when-you-really-need-it\">When you really need it</h2>\n<p>To take CQRS seriously, you should see these signals:</p>\n<ul>\n<li>High domain complexity — the write side carries serious business rules (the kind of domain where <a href=\"https://muhammetsafak.com/engineering/essays/layered-vs-clean-architecture/\">Clean Architecture</a> adds value).</li>\n<li>The shape and load of reads and writes are markedly different.</li>\n<li>Most often alongside <a href=\"https://muhammetsafak.com/engineering/notes/when-event-driven-architecture/\">event-driven architecture</a> — the read model is updated by events emitted from the write side.</li>\n</ul>\n<p>Without these signals, a single model with a separate read query when needed is more than enough.</p>\n<hr/>\n<p>CQRS is not a maturity badge; it’s the solution to a specific problem — reads and writes genuinely diverging. If you don’t have that problem, the only thing it buys you is the burden of keeping a second model in sync.</p>\n<p>Before you split the model, look at whether your reads and writes are truly separate.</p>",
      "content_text": "> **TL;DR:** CQRS separates the write model from the read model; that does not necessarily mean two databases or a read replica. It brings clarity in complex domains where the shape of writes and reads really diverges, and in plain CRUD it adds only a second model to keep in sync and twice the code. Lightweight CQRS starts with a separate query class.\n\nI once saw a codebase where a plain CRUD application claimed \"we implemented CQRS.\" A single \"create user\" operation had a Command, a CommandHandler, a separate read model, and a projection. All that ceremony ended in one line of `INSERT`.\n\nCQRS buys real clarity in some systems. In this application, the only thing it bought was twice the code.\n\n## What CQRS is, briefly\n\nCQRS — Command Query Responsibility Segregation — rests on a single idea: separate the **write model** from the **read model**.\n\nIn the classic approach a single model is both written and read — the same `Order` class both creates an order and renders it on screen. CQRS splits this in two: a write side that is a normalized model enforcing the rules; a read side that is a denormalized model shaped to the screen.\n\nNote: this does not necessarily mean two databases. Most of the time it means two **models** — they can live in the same database.\n\n## Don't confuse it with a read replica\n\nA common confusion: people think CQRS and a read replica are the same thing. They are not.\n\n- A **read replica** ([read/write splitting](/engineering/notes/read-write-splitting/)) is an infrastructure decision: same model, different server. To scale read load.\n- **CQRS** is a modeling decision: different model, same or different location. Because the **shape** of reads and writes has diverged.\n\nYou can use either one without the other. You can have a read replica but a single model; or do CQRS but on a single server. For a concrete case of that choice — heavy reporting reads against a few writes, replica first, outbox-fed projections only if query shapes diverge — see the Just Ask answer [When should I apply CQRS, and how do I sync the read and write models?](/just-ask/when-to-apply-cqrs-and-syncing-read-and-write-models/).\n\n## What CQRS buys you\n\nCQRS adds value when the write model and the read model **genuinely** diverge. That happens in complex domains: the shape you write drifts away from the shape you read.\n\nThe write side is a normalized model that enforces invariants and carries business rules. The read side is a model flattened to the needs of the screens, precomputed, fast to query. Forcing them into a single model makes both mediocre.\n\n## Dead weight in plain CRUD\n\nHere's the problem: in a plain CRUD application the write model and the read model are **already the same** — both are that row itself. Applying CQRS there is modeling a distinction that doesn't exist.\n\nThe result: two models, two structures that must be kept in sync, twice the code — and zero gain in return. This is [speculative generality](/engineering/essays/the-cost-of-just-in-case-code/) at the scale of a pattern: paying today for a complexity that doesn't exist today.\n\n## Lightweight CQRS\n\nTo \"do\" CQRS you don't need event sourcing, separate databases, or projection infrastructure. Those are the heaviest form of CQRS, not its mandatory form.\n\nA lightweight start: leave the write side on plain Eloquent models, and for the read side write a separate query class that returns a DTO shaped to the screen. The write and read paths are separated in code — which is the essence of CQRS already. Move to the heavy infrastructure only when you actually need it.\n\n\n> **Tan:** If the read model is updated through a separate flow after the write, a user may not see what they just saved. Before settling on CQRS, ask whether the product side can accept that delay. The lightweight form often takes this question off the table.\n\n\n## When you really need it\n\nTo take CQRS seriously, you should see these signals:\n\n- High domain complexity — the write side carries serious business rules (the kind of domain where [Clean Architecture](/engineering/essays/layered-vs-clean-architecture/) adds value).\n- The shape and load of reads and writes are markedly different.\n- Most often alongside [event-driven architecture](/engineering/notes/when-event-driven-architecture/) — the read model is updated by events emitted from the write side.\n\nWithout these signals, a single model with a separate read query when needed is more than enough.\n\n---\n\nCQRS is not a maturity badge; it's the solution to a specific problem — reads and writes genuinely diverging. If you don't have that problem, the only thing it buys you is the burden of keeping a second model in sync.\n\nBefore you split the model, look at whether your reads and writes are truly separate.",
      "date_published": "2026-10-03T00:00:00.000Z",
      "tags": [
        "architecture",
        "cqrs",
        "patterns"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/archiving-strategy/",
      "url": "https://muhammetsafak.com/engineering/notes/archiving-strategy/",
      "title": "An Archiving Strategy: Old Data Without the Slowdown",
      "summary": "When hot and cold data share one table, the cold rows slow every query: indexes bloat and autovacuum falls behind. Archiving is not a cleanup job but a lifecycle designed on day one. In a table partitioned by time, an old partition is detached with DETACH, moved to colder storage, and the door to it stays open.",
      "content_html": "<p>I once saw an <code>orders</code> table that had accumulated eight years of data. 95% of the queries looked at the last 90 days — but every query paid the price of the remaining eight years in index size and vacuum time. The hot data was carrying the weight of the cold data.</p>\n<p>No table can grow forever. Archiving is accepting that and planning for it from the start.</p>\n<h2 id=\"a-table-cant-grow-forever\">A table can’t grow forever</h2>\n<p>Most tables have a natural hot/cold split. Active data — this week’s orders, open tickets — is read and written constantly. Historical data — records closed three years ago — almost never changes and is rarely read. But when the two live in the same table, the cold data slows down every query against the hot data: indexes bloat, autovacuum can’t keep up, the working set grows artificially.</p>\n<h2 id=\"archiving-is-a-lifecycle\">Archiving is a lifecycle</h2>\n<p>Archiving isn’t a cleanup chore you think of once the table has grown large enough to cause panic. It’s a lifecycle for the data, and it should be designed on day one: data is born hot, cools over time, then turns cold. The question isn’t “will we archive,” it’s “where does the cooling data go.”</p>\n<h2 id=\"partition-based-archiving\">Partition-based archiving</h2>\n<p>The cleanest method is to partition the table by time — the structure described at the third breaking point of <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a>. In append-heavy data the natural key is time, and partitions make archiving nearly free.</p>\n<p>Instead of deleting an old partition, you <strong>detach</strong> it:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">ALTER</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> TABLE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders DETACH </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">PARTITION</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders_2023_01;</span></span></code></pre>\n<p>With <code>DETACH</code>, the partition breaks away from the main table but continues to exist in the database as a separate table. Now you can move it however you like — without deleting it, without freezing it.</p>\n<h2 id=\"cold-storage-options\">Cold storage options</h2>\n<p>Detached partitions can go to different places depending on cost and access needs:</p>\n<ul>\n<li><strong>A separate archive schema</strong> — same database but in an <code>archive</code> schema; queryable, just out of the hot path.</li>\n<li><strong>Cheaper disk</strong> — moving the partition’s files to a different tablespace.</li>\n<li><strong>Object storage</strong> — moving the partition into an S3-like store as a compressed dump or as Parquet; the cheapest, the slowest to access.</li>\n<li><strong>A separate archive database</strong> — fully independent of the live system’s capacity.</li>\n</ul>\n<h2 id=\"keeping-access-while-you-archive\">Keeping access while you archive</h2>\n<p>This is the hard part: archived data is often not entirely dead. An audit, a support request, a legal obligation can demand it again. Don’t confuse archiving with “making it inaccessible.”</p>\n<p>Practical balances: keeping archive tables queryable (just on cheap storage); reaching data in object storage via a foreign data wrapper; or leaving a separate path that is explicitly known as the “archive query,” slow but working. Whichever you choose, leave a door to the cold data — as long as that door is separate from the hot path.</p>\n<h2 id=\"deleting-is-an-archive-decision-too\">Deleting is an archive decision too</h2>\n<p>Sometimes the right archive is deletion. Not every piece of data needs to be kept; a retention policy answers the question “how long does this data live” from the start. Regulations like KVKK/GDPR already make deletion mandatory for some data. Design deletion as a step in the lifecycle too — not as an afterthought.</p>\n<hr/>\n<p>An archiving strategy starts with accepting on day one that the table will grow. The way to keep hot data fast is to stop cold data from being a burden on it.</p>\n<p>Your table will grow; the only question is whether you planned for it or production reminded you.</p>",
      "content_text": "> **TL;DR:** When hot and cold data share one table, the cold rows slow every query: indexes bloat and autovacuum falls behind. Archiving is not a cleanup job but a lifecycle designed on day one. In a table partitioned by time, an old partition is detached with DETACH, moved to colder storage, and the door to it stays open.\n\nI once saw an `orders` table that had accumulated eight years of data. 95% of the queries looked at the last 90 days — but every query paid the price of the remaining eight years in index size and vacuum time. The hot data was carrying the weight of the cold data.\n\nNo table can grow forever. Archiving is accepting that and planning for it from the start.\n\n## A table can't grow forever\n\nMost tables have a natural hot/cold split. Active data — this week's orders, open tickets — is read and written constantly. Historical data — records closed three years ago — almost never changes and is rarely read. But when the two live in the same table, the cold data slows down every query against the hot data: indexes bloat, autovacuum can't keep up, the working set grows artificially.\n\n## Archiving is a lifecycle\n\nArchiving isn't a cleanup chore you think of once the table has grown large enough to cause panic. It's a lifecycle for the data, and it should be designed on day one: data is born hot, cools over time, then turns cold. The question isn't \"will we archive,\" it's \"where does the cooling data go.\"\n\n## Partition-based archiving\n\nThe cleanest method is to partition the table by time — the structure described at the third breaking point of [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/). In append-heavy data the natural key is time, and partitions make archiving nearly free.\n\nInstead of deleting an old partition, you **detach** it:\n\n```sql\nALTER TABLE orders DETACH PARTITION orders_2023_01;\n```\n\nWith `DETACH`, the partition breaks away from the main table but continues to exist in the database as a separate table. Now you can move it however you like — without deleting it, without freezing it.\n\n## Cold storage options\n\nDetached partitions can go to different places depending on cost and access needs:\n\n- **A separate archive schema** — same database but in an `archive` schema; queryable, just out of the hot path.\n- **Cheaper disk** — moving the partition's files to a different tablespace.\n- **Object storage** — moving the partition into an S3-like store as a compressed dump or as Parquet; the cheapest, the slowest to access.\n- **A separate archive database** — fully independent of the live system's capacity.\n\n## Keeping access while you archive\n\nThis is the hard part: archived data is often not entirely dead. An audit, a support request, a legal obligation can demand it again. Don't confuse archiving with \"making it inaccessible.\"\n\nPractical balances: keeping archive tables queryable (just on cheap storage); reaching data in object storage via a foreign data wrapper; or leaving a separate path that is explicitly known as the \"archive query,\" slow but working. Whichever you choose, leave a door to the cold data — as long as that door is separate from the hot path.\n\n## Deleting is an archive decision too\n\nSometimes the right archive is deletion. Not every piece of data needs to be kept; a retention policy answers the question \"how long does this data live\" from the start. Regulations like KVKK/GDPR already make deletion mandatory for some data. Design deletion as a step in the lifecycle too — not as an afterthought.\n\n---\n\nAn archiving strategy starts with accepting on day one that the table will grow. The way to keep hot data fast is to stop cold data from being a burden on it.\n\nYour table will grow; the only question is whether you planned for it or production reminded you.\n\n## Sources\n\n- [PostgreSQL 18: Table Partitioning](https://www.postgresql.org/docs/18/ddl-partitioning.html) — PostgreSQL",
      "date_published": "2026-09-26T00:00:00.000Z",
      "tags": [
        "postgresql",
        "database",
        "performance",
        "production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/big-data-syndrome/",
      "url": "https://muhammetsafak.com/engineering/essays/big-data-syndrome/",
      "title": "Is Your Data Really Big, or Just Badly Modeled?",
      "summary": "A team that says our data is big usually rests on a feeling of slowness, not a measurement; a 12 GB table is small for a modern PostgreSQL. Moving to a distributed system before the data is genuinely big is the most expensive wrong turn; the tax is paid up front and nothing gets solved in return. If there is no number, what you have is not big data but unmeasured data.",
      "content_html": "<p>A sentence came up in a meeting: “Our data has grown so much, we need to move to a distributed database now.” Then we looked at the actual size: 12 GB. For PostgreSQL on a modern server, 12 GB isn’t big — it’s small.</p>\n<p>“Big data” is said most often about data that isn’t big at all. And that sentence isn’t a diagnosis; more often it’s an excuse.</p>\n<h2 id=\"big-is-a-feeling-not-a-measurement\">“Big” is a feeling, not a measurement</h2>\n<p>The sentence “our data is big” almost never rests on a number. It rests on a sense of slowness, a fear, a conference talk. Yet a modern PostgreSQL comfortably carries hundreds of GB on an ordinary server, and low TB if it’s set up carefully.</p>\n<p>Whether data is big isn’t felt; it’s measured. A “big” verdict reached without measuring is the first step toward the wrong architecture.</p>\n<h2 id=\"what-most-big-data-problems-actually-are\">What most “big data” problems actually are</h2>\n<p>The real cause of the slowness mistaken for big data is almost always one of three:</p>\n<ul>\n<li><strong>Missing index.</strong> A query doing a sequential scan makes a 5 GB table feel like 500 GB. The problem isn’t the size, it’s the scanned size.</li>\n<li><strong>Bad modeling.</strong> Unnormalized tables, giant JSON blobs embedded in every row, an append-heavy table that was never partitioned. The data isn’t “big,” it’s badly placed.</li>\n<li><strong>Wrong access pattern.</strong> N+1 queries, pulling the whole row when one column would do, queries inside a loop. The application uses small data in a big way.</li>\n</ul>\n<p>All three are solved by <strong>discipline</strong>, not by size — and none of the three requires a distributed database.</p>\n<h2 id=\"measuring-the-real-size\">Measuring the real size</h2>\n<p>To answer the “is it big” question, ask concrete questions:</p>\n<ul>\n<li>How much space does the table actually take? Look with <code>pg_total_relation_size</code> — not by guessing.</li>\n<li>Does the frequently accessed data (working set) fit in RAM? Has the cache hit ratio from <code>pg_stat_database</code> dropped below 99%?</li>\n<li>What’s the growth rate? 1 GB per month and 100 GB per month are entirely different decisions.</li>\n<li>Which query is slow, and <strong>why</strong>? What does the <code>EXPLAIN ANALYZE</code> output say?</li>\n</ul>\n<p>If the answers to these questions reveal a real breaking point, what to do next — index, read replica, partitioning — is in <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">the breaking points of data-intensive systems</a>. This piece is about the measurement that comes before those steps.</p>\n<h2 id=\"the-distributed-system-tax\">The distributed-system tax</h2>\n<p>Moving to a distributed system before the data is genuinely big is the most expensive wrong turn. Because you pay the costs <strong>up front</strong> — with manual sharding or <a href=\"https://muhammetsafak.com/engineering/essays/the-nosql-trap/\">distributed NoSQL</a>, losing the <code>JOIN</code> across tables and eventual consistency; even with distributed SQL, twice the operational load and distributed debugging — and nothing gets solved in return. A real tax for a problem that doesn’t exist.</p>\n<p>The rule from <a href=\"https://muhammetsafak.com/engineering/essays/is-postgresql-enough-for-everything/\">is PostgreSQL enough for everything</a> applies here too: most teams use a small fraction of PostgreSQL’s <code>jsonb</code>, partitioning, BRIN, and indexing capabilities and then conclude it “isn’t enough.”</p>\n<h2 id=\"if-it-really-is-big\">If it really is big</h2>\n<p>Let’s be honest: real big data exists. Throughput that sustainably exceeds the write capacity of a single large machine, or a genuinely multi-TB hot working set — these are real limits. A system that gets there has also reached a scale that can finance that complexity; at that point a distributed architecture isn’t a debt, it’s an earned cost.</p>\n<p>The point isn’t to be against distributed systems; it’s to avoid moving to them before they’re truly needed — that is, before measuring.</p>\n<hr/>\n<p>When you hear “our data is big,” the only thing to ask for is a number. If there’s no number, what you have isn’t big data, it’s unmeasured data.</p>\n<p>Real size is measured; felt size is, most of the time, a missing index.</p>",
      "content_text": "> **TL;DR:** A team that says our data is big usually rests on a feeling of slowness, not a measurement; a 12 GB table is small for a modern PostgreSQL. Moving to a distributed system before the data is genuinely big is the most expensive wrong turn; the tax is paid up front and nothing gets solved in return. If there is no number, what you have is not big data but unmeasured data.\n\nA sentence came up in a meeting: \"Our data has grown so much, we need to move to a distributed database now.\" Then we looked at the actual size: 12 GB. For PostgreSQL on a modern server, 12 GB isn't big — it's small.\n\n\"Big data\" is said most often about data that isn't big at all. And that sentence isn't a diagnosis; more often it's an excuse.\n\n## \"Big\" is a feeling, not a measurement\n\nThe sentence \"our data is big\" almost never rests on a number. It rests on a sense of slowness, a fear, a conference talk. Yet a modern PostgreSQL comfortably carries hundreds of GB on an ordinary server, and low TB if it's set up carefully.\n\nWhether data is big isn't felt; it's measured. A \"big\" verdict reached without measuring is the first step toward the wrong architecture.\n\n## What most \"big data\" problems actually are\n\nThe real cause of the slowness mistaken for big data is almost always one of three:\n\n- **Missing index.** A query doing a sequential scan makes a 5 GB table feel like 500 GB. The problem isn't the size, it's the scanned size.\n- **Bad modeling.** Unnormalized tables, giant JSON blobs embedded in every row, an append-heavy table that was never partitioned. The data isn't \"big,\" it's badly placed.\n- **Wrong access pattern.** N+1 queries, pulling the whole row when one column would do, queries inside a loop. The application uses small data in a big way.\n\nAll three are solved by **discipline**, not by size — and none of the three requires a distributed database.\n\n## Measuring the real size\n\nTo answer the \"is it big\" question, ask concrete questions:\n\n- How much space does the table actually take? Look with `pg_total_relation_size` — not by guessing.\n- Does the frequently accessed data (working set) fit in RAM? Has the cache hit ratio from `pg_stat_database` dropped below 99%?\n- What's the growth rate? 1 GB per month and 100 GB per month are entirely different decisions.\n- Which query is slow, and **why**? What does the `EXPLAIN ANALYZE` output say?\n\nIf the answers to these questions reveal a real breaking point, what to do next — index, read replica, partitioning — is in [the breaking points of data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/). This piece is about the measurement that comes before those steps.\n\n## The distributed-system tax\n\nMoving to a distributed system before the data is genuinely big is the most expensive wrong turn. Because you pay the costs **up front** — with manual sharding or [distributed NoSQL](/engineering/essays/the-nosql-trap/), losing the `JOIN` across tables and eventual consistency; even with distributed SQL, twice the operational load and distributed debugging — and nothing gets solved in return. A real tax for a problem that doesn't exist.\n\nThe rule from [is PostgreSQL enough for everything](/engineering/essays/is-postgresql-enough-for-everything/) applies here too: most teams use a small fraction of PostgreSQL's `jsonb`, partitioning, BRIN, and indexing capabilities and then conclude it \"isn't enough.\"\n\n## If it really is big\n\nLet's be honest: real big data exists. Throughput that sustainably exceeds the write capacity of a single large machine, or a genuinely multi-TB hot working set — these are real limits. A system that gets there has also reached a scale that can finance that complexity; at that point a distributed architecture isn't a debt, it's an earned cost.\n\nThe point isn't to be against distributed systems; it's to avoid moving to them before they're truly needed — that is, before measuring.\n\n---\n\nWhen you hear \"our data is big,\" the only thing to ask for is a number. If there's no number, what you have isn't big data, it's unmeasured data.\n\nReal size is measured; felt size is, most of the time, a missing index.",
      "date_published": "2026-09-19T00:00:00.000Z",
      "tags": [
        "database",
        "scaling",
        "architecture",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/sizing-a-postgres-queue-table-by-its-live-set/",
      "url": "https://muhammetsafak.com/engineering/notes/sizing-a-postgres-queue-table-by-its-live-set/",
      "title": "Sizing a PostgreSQL Queue Table by Its Live Set",
      "summary": "On a queue table the set doing the work is the pending rows, while the table grows forever with finished ones. Anything that scales with the table scales wrong: at 10 million rows a composite index reached 310 MB while a partial index stayed at 7.6 MB, and the default autovacuum threshold never caught the 1.75 million dead tuples that piled up in fifteen minutes.",
      "content_html": "<p>On a ten-million-row <code>jobs</code> table, 5,000 jobs were waiting in the queue, and the index the claim query used took up 310 MB. A 7.6 MB partial index did the same job, and the speed difference between the two was 6.9 percent.</p>\n<p>So the question was never speed. It was what grows along with the table.</p>\n<h2 id=\"a-queue-table-is-two-tables\">A queue table is two tables</h2>\n<p>Two separate sets live in a queue table:</p>\n<ul>\n<li><strong>The live set</strong> — the rows in <code>pending</code>. The part that workers look for, that claims lock, and that actually does the work. Its size depends on the balance between throughput and the arrival rate; in a healthy system it stays roughly constant.</li>\n<li><strong>The archive</strong> — the rows in <code>done</code>. Nobody queries them, but as long as they are not deleted the table grows with them forever.</li>\n</ul>\n<p>PostgreSQL does not know about this split. From MVCC’s point of view a finished row is a <strong>live tuple</strong>: <code>pg_class.reltuples</code> counts it, the planner statistics count it, the autovacuum threshold counts it. In the table I measured there were 5,000 <code>pending</code> rows and an <code>n_live_tup</code> of 10,005,726.</p>\n<p>That is why two wrong scalings happen on a queue table by themselves: the index grows with the table, and so does the vacuum threshold. Both look at the archive, not at the set doing the work.</p>\n<p>The numbers below come from <a href=\"https://github.com/muhammetsafak/pg-queue-bench\">pg-queue-bench</a>: PostgreSQL 17, one container, <code>shared_buffers</code> 1 GB, 8 clients, claims with <code>FOR UPDATE SKIP LOCKED</code>. Every pgbench transcript is in the repository.</p>\n<h2 id=\"index-the-queue-not-the-table\">Index the queue, not the table</h2>\n<p>The live set was held at 5,000 rows at every size; the only thing that changed was how many finished rows surrounded it. Claims per second, median of three repeats:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 1\"><table><thead><tr><th>Strategy</th><th>100k</th><th>1M</th><th>10M</th><th>Index size (10M)</th></tr></thead><tbody><tr><td>no index</td><td>2,001</td><td>248</td><td>8</td><td>—</td></tr><tr><td><code>(status)</code></td><td>6,500</td><td>6,417</td><td>6,426</td><td>66.1 MB</td></tr><tr><td><code>(status, created_at)</code></td><td>12,415</td><td>11,203</td><td>10,796</td><td>310.4 MB</td></tr><tr><td>partial <code>(created_at) WHERE status = &#39;pending&#39;</code></td><td>13,041</td><td>11,708</td><td>11,538</td><td>7.6 MB</td></tr></tbody></table></div>\n<p>The no-index row shows why the question exists at all: finding 5,000 rows among 10 million with a sequential scan can be done only 7.6 times a second.</p>\n<p>The throughput difference between composite and partial is 6.9 percent. That is not a reason to pick a partial index. The reason is size:</p>\n<ul>\n<li>The composite index grew with the table: 11.2 → 40.3 → 310.4 MB.</li>\n<li>The partial index stopped at 6.5 → 7.6 → 7.6 MB. What it indexes is not the table but the <strong>queue</strong>, and the queue is constant, so the index is too.</li>\n</ul>\n<p>At ten million rows the difference is <strong>41 times</strong>. Keeping a 310 MB index in <code>shared_buffers</code> and keeping a 7.6 MB one are not the same decision.</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">CREATE</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> INDEX</span><span style=\"color:#6F42C1;--shiki-dark:#B392F0\"> CONCURRENTLY</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> jobs_pending_created_at</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">    ON</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> jobs (created_at)</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\"> WHERE</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> status</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> &#39;pending&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p><code>ORDER BY created_at</code> gets its ordering from the index for free; the claim query must write the predicate <strong>exactly as the index does</strong>. Building the index with <code>CONCURRENTLY</code> on a live table is how you avoid blocking writes; <a href=\"https://muhammetsafak.com/engineering/notes/zero-downtime-database-migrations/\">the rest of zero-downtime schema change</a> is covered in its own piece.</p>\n<h3 id=\"if-you-ask-with-a-parameter\">If you ask with a parameter</h3>\n<p>PostgreSQL uses a partial index only if it can prove, <strong>at planning time</strong>, that the query’s <code>WHERE</code> clause implies the index predicate. A generic plan is built without knowing what <code>$1</code> is; it cannot prove that <code>status = $1</code> means <code>status = &#39;pending&#39;</code>, so it has to drop the partial index.</p>\n<p>Claims that ran at 11,752 per second under <code>force_custom_plan</code> fell to 7.2 when I forced <code>force_generic_plan</code>, and mean latency went from 0.68 ms to 1,113 ms — roughly <strong>1,635 times</strong>. The index’s scan counter stayed at zero. Under the same condition the composite index was untouched (11,417 per second), because it has no predicate to prove; <code>status</code> is a column inside the index.</p>\n<p>The cliff is real but fenced. In the default <code>auto</code> mode PostgreSQL runs the first five executions on custom plans, then compares the generic plan’s estimated cost against the average of the custom ones. In a single session, <strong>40 out of 40</strong> executions used a custom plan; the planner never switched to a generic one. I did not record plan costs; the likeliest explanation is that a generic plan, unable to use the partial index, comes out with a high estimated cost. It may not be the only reason, though: the <code>(status)</code> index, which has no predicate, also stayed on custom plans for all 40 executions. The composite index switched to a generic plan at the sixth execution and lost nothing by it.</p>\n<p>That protection has a price: a query that reaches the partial index is <strong>re-planned on every execution</strong>. At this scale the difference is too small to measure (averaged over the last five executions: partial 0.20 ms, composite 0.21 ms). The same cannot be said for a many-table join or a long <code>IN</code> list.</p>\n<p>The rule: <strong>do not reach a predicated index through a parameter.</strong> Write <code>status = &#39;pending&#39;</code> as a literal, and leave <code>plan_cache_mode</code> alone.</p>\n<h2 id=\"a-small-index-does-not-mean-less-vacuuming\">A small index does not mean less vacuuming</h2>\n<p>In thirty-second runs the two indexes were nearly equal. Under fifteen minutes of sustained load the picture changed. In this run the claimed row was set to <code>done</code>, and a producer ran alongside at 2,000 jobs per second.</p>\n<p>The partial index went <strong>from 0.125 MB to 38.2 MB</strong> — roughly 305 times. The live set stayed between 3,000 and 5,000 rows for most of the run; what grew was the dead entries in the index.</p>\n<p>The mechanism fits in one sentence: the <code>pending → done</code> transition takes the row out of the partial index’s scope, but its entry stays in the index until vacuum arrives. The partial index’s <strong>smallness comes from the live set</strong>, its <strong>bloat rate comes from throughput</strong>, and nothing connects the two. A small index makes vacuum cheaper, not rarer.</p>\n<h2 id=\"the-autovacuum-threshold-looks-at-the-archive\">The autovacuum threshold looks at the archive</h2>\n<p>In fifteen minutes 1,753,949 dead tuples piled up. The autovacuum counter: <strong>0</strong>.</p>\n<p>The default threshold is computed like this:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"plaintext\"><code><span class=\"line\"><span>vacuum threshold = autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples</span></span>\n<span class=\"line\"><span>                 = 50 + 0.2 × ~10,000,000</span></span>\n<span class=\"line\"><span>                 ≈ 2,000,000 dead tuples</span></span></code></pre>\n<p>Because <code>reltuples</code> counts finished rows too, the threshold grows with the archive. The set doing the work stays constant and dead tuples arrive at the rate of throughput, but the number vacuum waits for drifts a little further away with every new <code>done</code> row. The bigger the table, the later vacuum comes.</p>\n<p>The composite index paid for it. In the same fifteen minutes it went from 301 MB to 427 MB and fell behind the target:</p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div class=\"table-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Table 2\"><table><thead><tr><th>Strategy</th><th>At the start</th><th>At 900 s</th><th>Pending jobs</th></tr></thead><tbody><tr><td>partial</td><td>2,024 tps · 1.7 ms</td><td>2,016 tps · 4,906 ms</td><td>5,003 → 14,364</td></tr><tr><td>composite</td><td>2,000 tps · 0.52 ms</td><td>1,204 tps · 61,533 ms</td><td>5,000 → 126,024</td></tr></tbody></table></div>\n<p>Latency includes pgbench’s scheduling lag; a client that cannot keep to the target rate books its debt there. The partial index slipped too in the last 45 seconds (1,740 tps at 855 s, pending jobs from 4,549 to 14,364), but it finished the run at the target rate. The composite index never recovered after 660 s.</p>\n<h2 id=\"cut-the-threshold-loose-from-the-table\">Cut the threshold loose from the table</h2>\n<p>The global default was not designed for this access pattern. Cut the threshold loose from the table’s size and pin it to a fixed number:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">ALTER</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> TABLE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> jobs </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">SET</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> (</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">    autovacuum_vacuum_scale_factor </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> 0</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">    autovacuum_vacuum_threshold    </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> 50000</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">);</span></span></code></pre>\n<p><code>scale_factor = 0</code> makes the threshold independent of <code>reltuples</code>; only the fixed base remains. The right number is set by <strong>throughput</strong>, not table size: a queue processing 2,000 claims per second produces 50,000 dead tuples in about 25 seconds.</p>\n<p>I did not measure this setting — the run above used the defaults, and because autovacuum never ran, the <strong>cost</strong> of vacuuming was not measured either. 50,000 is a starting point; tune it to your own throughput and to how long vacuum takes on your own table.</p>\n<h2 id=\"measure-your-own-table\">Measure your own table</h2>\n<p>First, look at the ratio between the two sets:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> status</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">, </span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">count</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">(</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">*</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">)</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">  FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> jobs</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\"> GROUP BY</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> status</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p>Then at the size of the indexes, and whether they are used at all:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> indexrelname,</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">       pg_size_pretty(pg_relation_size(indexrelid)) </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">AS</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> size</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">       idx_scan</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">  FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> pg_stat_user_indexes</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\"> WHERE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> relname </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> &#39;jobs&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p>Finally, put the dead tuple count next to the global threshold:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> s</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">n_dead_tup</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">       s</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">autovacuum_count</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">       s</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">last_autovacuum</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">       current_setting(</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;autovacuum_vacuum_threshold&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">)::</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">int</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">         +</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> current_setting(</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;autovacuum_vacuum_scale_factor&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">)::float8 </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">*</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> c</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">reltuples</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">         AS</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> global_threshold,</span></span>\n<span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">       c</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">reloptions</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">  FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> pg_stat_user_tables s</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">  JOIN</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> pg_class c </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">ON</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> c</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">oid</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> s</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">relid</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\"> WHERE</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> s</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">relname</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> &#39;jobs&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p>A <code>reltuples</code> of -1 means the table has not been analyzed yet and the calculation is meaningless. An empty <code>reloptions</code> means the table uses the global threshold. If <code>n_dead_tup</code> keeps growing below <code>global_threshold</code> for hours while <code>autovacuum_count</code> stands still, your vacuum is looking at the archive.</p>\n<h2 id=\"when-to-drop-this-pattern\">When to drop this pattern</h2>\n<ul>\n<li><strong>You delete finished rows right away, or <a href=\"https://muhammetsafak.com/engineering/notes/archiving-strategy/\">move them to an archive table</a>.</strong> The table stays close to its live set, so both the composite index’s growth and the default threshold’s drift stay small.</li>\n<li><strong>Your ORM or driver binds <code>status</code> as a parameter and a generic plan is forced.</strong> You cannot use the partial index; a composite index is safer.</li>\n<li><strong>You partition the table by time.</strong> Dropping old partitions separates both the index and the vacuum load from the table’s size; it solves the problem this note solves by another route.</li>\n</ul>\n<p>The numbers come from one machine, PostgreSQL 17 and one access pattern. Thirty-second and fifteen-minute runs do not stand in for months of a real queue; the direction holds, the magnitudes belong to your workload.</p>\n<hr/>\n<p>On a queue table, table size is noise. Size the index and the vacuum to the set doing the work.</p>",
      "content_text": "> **TL;DR:** On a queue table the set doing the work is the pending rows, while the table grows forever with finished ones. Anything that scales with the table scales wrong: at 10 million rows a composite index reached 310 MB while a partial index stayed at 7.6 MB, and the default autovacuum threshold never caught the 1.75 million dead tuples that piled up in fifteen minutes.\n\nOn a ten-million-row `jobs` table, 5,000 jobs were waiting in the queue, and the index the claim query used took up 310 MB. A 7.6 MB partial index did the same job, and the speed difference between the two was 6.9 percent.\n\nSo the question was never speed. It was what grows along with the table.\n\n## A queue table is two tables\n\nTwo separate sets live in a queue table:\n\n- **The live set** — the rows in `pending`. The part that workers look for, that claims lock, and that actually does the work. Its size depends on the balance between throughput and the arrival rate; in a healthy system it stays roughly constant.\n- **The archive** — the rows in `done`. Nobody queries them, but as long as they are not deleted the table grows with them forever.\n\nPostgreSQL does not know about this split. From MVCC's point of view a finished row is a **live tuple**: `pg_class.reltuples` counts it, the planner statistics count it, the autovacuum threshold counts it. In the table I measured there were 5,000 `pending` rows and an `n_live_tup` of 10,005,726.\n\nThat is why two wrong scalings happen on a queue table by themselves: the index grows with the table, and so does the vacuum threshold. Both look at the archive, not at the set doing the work.\n\nThe numbers below come from [pg-queue-bench](https://github.com/muhammetsafak/pg-queue-bench): PostgreSQL 17, one container, `shared_buffers` 1 GB, 8 clients, claims with `FOR UPDATE SKIP LOCKED`. Every pgbench transcript is in the repository.\n\n## Index the queue, not the table\n\nThe live set was held at 5,000 rows at every size; the only thing that changed was how many finished rows surrounded it. Claims per second, median of three repeats:\n\n| Strategy | 100k | 1M | 10M | Index size (10M) |\n| --- | --- | --- | --- | --- |\n| no index | 2,001 | 248 | 8 | — |\n| `(status)` | 6,500 | 6,417 | 6,426 | 66.1 MB |\n| `(status, created_at)` | 12,415 | 11,203 | 10,796 | 310.4 MB |\n| partial `(created_at) WHERE status = 'pending'` | 13,041 | 11,708 | 11,538 | 7.6 MB |\n\nThe no-index row shows why the question exists at all: finding 5,000 rows among 10 million with a sequential scan can be done only 7.6 times a second.\n\nThe throughput difference between composite and partial is 6.9 percent. That is not a reason to pick a partial index. The reason is size:\n\n- The composite index grew with the table: 11.2 → 40.3 → 310.4 MB.\n- The partial index stopped at 6.5 → 7.6 → 7.6 MB. What it indexes is not the table but the **queue**, and the queue is constant, so the index is too.\n\nAt ten million rows the difference is **41 times**. Keeping a 310 MB index in `shared_buffers` and keeping a 7.6 MB one are not the same decision.\n\n```sql\nCREATE INDEX CONCURRENTLY jobs_pending_created_at\n    ON jobs (created_at)\n WHERE status = 'pending';\n```\n\n`ORDER BY created_at` gets its ordering from the index for free; the claim query must write the predicate **exactly as the index does**. Building the index with `CONCURRENTLY` on a live table is how you avoid blocking writes; [the rest of zero-downtime schema change](/engineering/notes/zero-downtime-database-migrations/) is covered in its own piece.\n\n### If you ask with a parameter\n\nPostgreSQL uses a partial index only if it can prove, **at planning time**, that the query's `WHERE` clause implies the index predicate. A generic plan is built without knowing what `$1` is; it cannot prove that `status = $1` means `status = 'pending'`, so it has to drop the partial index.\n\nClaims that ran at 11,752 per second under `force_custom_plan` fell to 7.2 when I forced `force_generic_plan`, and mean latency went from 0.68 ms to 1,113 ms — roughly **1,635 times**. The index's scan counter stayed at zero. Under the same condition the composite index was untouched (11,417 per second), because it has no predicate to prove; `status` is a column inside the index.\n\nThe cliff is real but fenced. In the default `auto` mode PostgreSQL runs the first five executions on custom plans, then compares the generic plan's estimated cost against the average of the custom ones. In a single session, **40 out of 40** executions used a custom plan; the planner never switched to a generic one. I did not record plan costs; the likeliest explanation is that a generic plan, unable to use the partial index, comes out with a high estimated cost. It may not be the only reason, though: the `(status)` index, which has no predicate, also stayed on custom plans for all 40 executions. The composite index switched to a generic plan at the sixth execution and lost nothing by it.\n\nThat protection has a price: a query that reaches the partial index is **re-planned on every execution**. At this scale the difference is too small to measure (averaged over the last five executions: partial 0.20 ms, composite 0.21 ms). The same cannot be said for a many-table join or a long `IN` list.\n\nThe rule: **do not reach a predicated index through a parameter.** Write `status = 'pending'` as a literal, and leave `plan_cache_mode` alone.\n\n## A small index does not mean less vacuuming\n\nIn thirty-second runs the two indexes were nearly equal. Under fifteen minutes of sustained load the picture changed. In this run the claimed row was set to `done`, and a producer ran alongside at 2,000 jobs per second.\n\nThe partial index went **from 0.125 MB to 38.2 MB** — roughly 305 times. The live set stayed between 3,000 and 5,000 rows for most of the run; what grew was the dead entries in the index.\n\nThe mechanism fits in one sentence: the `pending → done` transition takes the row out of the partial index's scope, but its entry stays in the index until vacuum arrives. The partial index's **smallness comes from the live set**, its **bloat rate comes from throughput**, and nothing connects the two. A small index makes vacuum cheaper, not rarer.\n\n## The autovacuum threshold looks at the archive\n\nIn fifteen minutes 1,753,949 dead tuples piled up. The autovacuum counter: **0**.\n\nThe default threshold is computed like this:\n\n```\nvacuum threshold = autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples\n                 = 50 + 0.2 × ~10,000,000\n                 ≈ 2,000,000 dead tuples\n```\n\nBecause `reltuples` counts finished rows too, the threshold grows with the archive. The set doing the work stays constant and dead tuples arrive at the rate of throughput, but the number vacuum waits for drifts a little further away with every new `done` row. The bigger the table, the later vacuum comes.\n\nThe composite index paid for it. In the same fifteen minutes it went from 301 MB to 427 MB and fell behind the target:\n\n| Strategy | At the start | At 900 s | Pending jobs |\n| --- | --- | --- | --- |\n| partial | 2,024 tps · 1.7 ms | 2,016 tps · 4,906 ms | 5,003 → 14,364 |\n| composite | 2,000 tps · 0.52 ms | 1,204 tps · 61,533 ms | 5,000 → 126,024 |\n\nLatency includes pgbench's scheduling lag; a client that cannot keep to the target rate books its debt there. The partial index slipped too in the last 45 seconds (1,740 tps at 855 s, pending jobs from 4,549 to 14,364), but it finished the run at the target rate. The composite index never recovered after 660 s.\n\n## Cut the threshold loose from the table\n\nThe global default was not designed for this access pattern. Cut the threshold loose from the table's size and pin it to a fixed number:\n\n```sql\nALTER TABLE jobs SET (\n    autovacuum_vacuum_scale_factor = 0,\n    autovacuum_vacuum_threshold    = 50000\n);\n```\n\n`scale_factor = 0` makes the threshold independent of `reltuples`; only the fixed base remains. The right number is set by **throughput**, not table size: a queue processing 2,000 claims per second produces 50,000 dead tuples in about 25 seconds.\n\nI did not measure this setting — the run above used the defaults, and because autovacuum never ran, the **cost** of vacuuming was not measured either. 50,000 is a starting point; tune it to your own throughput and to how long vacuum takes on your own table.\n\n## Measure your own table\n\nFirst, look at the ratio between the two sets:\n\n```sql\nSELECT status, count(*)\n  FROM jobs\n GROUP BY status;\n```\n\nThen at the size of the indexes, and whether they are used at all:\n\n```sql\nSELECT indexrelname,\n       pg_size_pretty(pg_relation_size(indexrelid)) AS size,\n       idx_scan\n  FROM pg_stat_user_indexes\n WHERE relname = 'jobs';\n```\n\nFinally, put the dead tuple count next to the global threshold:\n\n```sql\nSELECT s.n_dead_tup,\n       s.autovacuum_count,\n       s.last_autovacuum,\n       current_setting('autovacuum_vacuum_threshold')::int\n         + current_setting('autovacuum_vacuum_scale_factor')::float8 * c.reltuples\n         AS global_threshold,\n       c.reloptions\n  FROM pg_stat_user_tables s\n  JOIN pg_class c ON c.oid = s.relid\n WHERE s.relname = 'jobs';\n```\n\nA `reltuples` of -1 means the table has not been analyzed yet and the calculation is meaningless. An empty `reloptions` means the table uses the global threshold. If `n_dead_tup` keeps growing below `global_threshold` for hours while `autovacuum_count` stands still, your vacuum is looking at the archive.\n\n## When to drop this pattern\n\n- **You delete finished rows right away, or [move them to an archive table](/engineering/notes/archiving-strategy/).** The table stays close to its live set, so both the composite index's growth and the default threshold's drift stay small.\n- **Your ORM or driver binds `status` as a parameter and a generic plan is forced.** You cannot use the partial index; a composite index is safer.\n- **You partition the table by time.** Dropping old partitions separates both the index and the vacuum load from the table's size; it solves the problem this note solves by another route.\n\nThe numbers come from one machine, PostgreSQL 17 and one access pattern. Thirty-second and fifteen-minute runs do not stand in for months of a real queue; the direction holds, the magnitudes belong to your workload.\n\n---\n\nOn a queue table, table size is noise. Size the index and the vacuum to the set doing the work.\n\n## Sources\n\n- [Routine Vacuuming: the autovacuum daemon and its thresholds](https://www.postgresql.org/docs/17/routine-vacuuming.html) — PostgreSQL\n- [Partial Indexes](https://www.postgresql.org/docs/17/indexes-partial.html) — PostgreSQL\n- [PREPARE: generic and custom plans](https://www.postgresql.org/docs/17/sql-prepare.html) — PostgreSQL\n- [pg-queue-bench: raw pgbench runs behind every number in this note](https://github.com/muhammetsafak/pg-queue-bench) — GitHub\n\n## Frequently asked\n\n### Is a partial index faster on a queue table?\n\nNot meaningfully. On a table with 10 million finished rows the partial index carried 11,538 claims per second and the (status, created_at) composite index 10,796; the difference is 6.9 percent. The real difference is size: the partial index held at 7.6 MB while the composite one reached 310 MB.\n\n### Why does autovacuum reach a queue table so late?\n\nThe default threshold is 50 + 0.2 × reltuples, and reltuples counts finished rows too. On a 10-million-row table that is roughly 2 million dead tuples; in the measurement 1.75 million dead tuples piled up in fifteen minutes and autovacuum did not run once. As the table grows, so does the threshold.",
      "date_published": "2026-09-16T00:00:00.000Z",
      "date_modified": "2026-10-07T00:00:00.000Z",
      "tags": [
        "postgresql",
        "queue",
        "performance",
        "indexing",
        "production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/orm-vs-native-sql/",
      "url": "https://muhammetsafak.com/engineering/essays/orm-vs-native-sql/",
      "title": "ORM or Native SQL?",
      "summary": "An ORM is the right default for CRUD: it binds parameters and cuts repetition. Its danger is what it hides — N+1 queries, whole rows pulled for one column, a forgotten where. For multi-table reports, aggregations and bulk operations plain SQL is faster and clearer, and what keeps a query safe is parameter binding, not the tool.",
      "content_html": "<p>A single page of an admin panel was firing 1,400 queries. The cause wasn’t visible on screen: inside a loop, the innocent-looking <code>$order-&gt;customer-&gt;name</code> call fired a separate query for every order. The ORM hadn’t actually hidden anything — it had only let the developer stop thinking about which query was running.</p>\n<p>Is the ORM making us lazy, or protecting us? The answer is both — and the team decides which one dominates.</p>\n<h2 id=\"what-an-orm-buys-you\">What an ORM buys you</h2>\n<p>The ORM has real upsides, and they shouldn’t be dismissed:</p>\n<ul>\n<li><strong>Safety.</strong> Queries are parameterized by default; under ordinary use, the SQL injection surface is closed.</li>\n<li><strong>Readability.</strong> For CRUD operations, <code>User::create($data)</code> is shorter and clearer than a hand-written <code>INSERT</code>.</li>\n<li><strong>Less repetition.</strong> Relationships, migrations, model events — all in one place.</li>\n</ul>\n<p>The vast majority of projects are CRUD at their core, and for that work the ORM is the right default. I have no objection to that.</p>\n<h2 id=\"where-the-orm-makes-you-lazy\">Where the ORM makes you lazy</h2>\n<p>The danger isn’t in what the ORM does, but in what it <strong>hides</strong>. The ORM keeps SQL out of sight; and when the developer can’t see the SQL, they stop thinking about which query is running.</p>\n<p>The result is familiar: the N+1 from the opening of this piece; pulling a whole row into memory when a single column would do; forgetting a <code>where</code> and unknowingly loading an entire table. The ORM doesn’t “do” any of these; they’re all done by the developer who never looks at what the ORM produces.</p>\n<p>In the <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a> piece, the first row of the false-breaking-points table is exactly this: what looks like “the database is slow” is, most of the time, the application firing 200 queries.</p>\n<h2 id=\"where-the-orm-ends\">Where the ORM ends</h2>\n<p>The ORM shines at transactional CRUD: create a record, update it, read it with its relationships. Where it struggles is just as clear:</p>\n<ul>\n<li>Multi-table, multi-step reports.</li>\n<li>Aggregations, window functions, complex conditions on top of <code>GROUP BY</code>.</li>\n<li>Bulk operations — a single <code>UPDATE</code> instead of walking millions of rows one model at a time.</li>\n</ul>\n<p>For this kind of work, insisting on the ORM produces code that is both slower and less readable. Plain SQL is both faster and clearer here. Picking the right indexes is part of this work too — the <a href=\"https://muhammetsafak.com/engineering/notes/index-management/\">index management</a> note covers that side.</p>\n<h2 id=\"the-call-orm-as-default-sql-as-a-tool\">The call: ORM as default, SQL as a tool</h2>\n<p>The two aren’t rivals. The right use is roughly this:</p>\n<ul>\n<li>90% of the work — CRUD, simple lists — with the ORM. Fast, safe, readable.</li>\n<li>The remaining 10% — heavy reporting, aggregation, bulk operations — with the query builder or plain SQL.</li>\n</ul>\n<p>The mark of seniority isn’t knowing the ORM; it’s knowing <strong>where it ends</strong>. A team that forces the ORM onto everything turns it into a performance trap; a team that never uses the ORM and writes everything by hand gives up safety and readability for nothing.</p>\n<h2 id=\"both-can-be-written-safely\">Both can be written safely</h2>\n<p>A common mistake: “plain SQL = unsafe.” What provides safety isn’t the ORM; it’s <strong>parameter binding</strong>. A plain query written with bound parameters is as closed to injection as the ORM:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"php\"><code><span class=\"line\"><span style=\"color:#005CC5;--shiki-dark:#79B8FF\">DB</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">::</span><span style=\"color:#6F42C1;--shiki-dark:#B392F0\">select</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">(</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> id, total </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">FROM</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> orders </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">WHERE</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> status</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> ?&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">, [</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;pending&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">]);</span></span></code></pre>\n<p>What’s dangerous isn’t plain SQL; it’s embedding user input into the query through string concatenation — and you can do that inside the ORM’s <code>whereRaw</code> too. The habit protects you, not the tool.</p>\n<hr/>\n<p>The ORM can be a laziness machine or a safety net — the difference is made by how the team looks at it. Use it, but never stop seeing what it produces.</p>\n<p>A good developer writes with the ORM; they also know when to put it down.</p>",
      "content_text": "> **TL;DR:** An ORM is the right default for CRUD: it binds parameters and cuts repetition. Its danger is what it hides — N+1 queries, whole rows pulled for one column, a forgotten where. For multi-table reports, aggregations and bulk operations plain SQL is faster and clearer, and what keeps a query safe is parameter binding, not the tool.\n\nA single page of an admin panel was firing 1,400 queries. The cause wasn't visible on screen: inside a loop, the innocent-looking `$order->customer->name` call fired a separate query for every order. The ORM hadn't actually hidden anything — it had only let the developer stop thinking about which query was running.\n\nIs the ORM making us lazy, or protecting us? The answer is both — and the team decides which one dominates.\n\n## What an ORM buys you\n\nThe ORM has real upsides, and they shouldn't be dismissed:\n\n- **Safety.** Queries are parameterized by default; under ordinary use, the SQL injection surface is closed.\n- **Readability.** For CRUD operations, `User::create($data)` is shorter and clearer than a hand-written `INSERT`.\n- **Less repetition.** Relationships, migrations, model events — all in one place.\n\nThe vast majority of projects are CRUD at their core, and for that work the ORM is the right default. I have no objection to that.\n\n## Where the ORM makes you lazy\n\nThe danger isn't in what the ORM does, but in what it **hides**. The ORM keeps SQL out of sight; and when the developer can't see the SQL, they stop thinking about which query is running.\n\nThe result is familiar: the N+1 from the opening of this piece; pulling a whole row into memory when a single column would do; forgetting a `where` and unknowingly loading an entire table. The ORM doesn't \"do\" any of these; they're all done by the developer who never looks at what the ORM produces.\n\nIn the [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/) piece, the first row of the false-breaking-points table is exactly this: what looks like \"the database is slow\" is, most of the time, the application firing 200 queries.\n\n## Where the ORM ends\n\nThe ORM shines at transactional CRUD: create a record, update it, read it with its relationships. Where it struggles is just as clear:\n\n- Multi-table, multi-step reports.\n- Aggregations, window functions, complex conditions on top of `GROUP BY`.\n- Bulk operations — a single `UPDATE` instead of walking millions of rows one model at a time.\n\nFor this kind of work, insisting on the ORM produces code that is both slower and less readable. Plain SQL is both faster and clearer here. Picking the right indexes is part of this work too — the [index management](/engineering/notes/index-management/) note covers that side.\n\n## The call: ORM as default, SQL as a tool\n\nThe two aren't rivals. The right use is roughly this:\n\n- 90% of the work — CRUD, simple lists — with the ORM. Fast, safe, readable.\n- The remaining 10% — heavy reporting, aggregation, bulk operations — with the query builder or plain SQL.\n\nThe mark of seniority isn't knowing the ORM; it's knowing **where it ends**. A team that forces the ORM onto everything turns it into a performance trap; a team that never uses the ORM and writes everything by hand gives up safety and readability for nothing.\n\n## Both can be written safely\n\nA common mistake: \"plain SQL = unsafe.\" What provides safety isn't the ORM; it's **parameter binding**. A plain query written with bound parameters is as closed to injection as the ORM:\n\n```php\nDB::select('SELECT id, total FROM orders WHERE status = ?', ['pending']);\n```\n\nWhat's dangerous isn't plain SQL; it's embedding user input into the query through string concatenation — and you can do that inside the ORM's `whereRaw` too. The habit protects you, not the tool.\n\n---\n\nThe ORM can be a laziness machine or a safety net — the difference is made by how the team looks at it. Use it, but never stop seeing what it produces.\n\nA good developer writes with the ORM; they also know when to put it down.\n\n## Sources\n\n- [Database: Query Builder (Laravel 12.x)](https://laravel.com/docs/12.x/queries) — Laravel",
      "date_published": "2026-09-12T00:00:00.000Z",
      "tags": [
        "database",
        "orm",
        "sql",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/index-management/",
      "url": "https://muhammetsafak.com/engineering/notes/index-management/",
      "title": "Indexes: Too Few Slow Reads, Too Many Kill Writes",
      "summary": "An index is not free read speed; it is read speed paid for with writes. Every INSERT writes an entry into every index on the table, and an UPDATE does the same the moment it touches an indexed column. A HOT update and a partial index are the exceptions, not the default. So add an index because a real query plan asked for it, and drop one because pg_stat_user_indexes shows idx_scan = 0.",
      "content_html": "<p>I’ve seen two opposite teams. One had put no indexes on the table at all — every query a sequential scan, every list page taking seconds. The other had done the exact opposite: “just in case,” it had created an index on every column, and now every <code>INSERT</code> crawled along.</p>\n<p>Both are two ends of the same fallacy: thinking an index is a free source of speed.</p>\n<h2 id=\"an-index-is-not-free-speed\">An index is not free speed</h2>\n<p>An index speeds up reads, because instead of scanning the whole table the database looks at an ordered structure. But that ordered structure doesn’t stay current on its own: an <code>INSERT</code> writes an entry into <strong>every index</strong> on the table, and an <code>UPDATE</code> does the same as soon as it touches an indexed column. There are exceptions — a HOT update that changes no indexed column leaves the indexes alone, a partial index is skipped for rows outside its <code>WHERE</code> clause, and a <code>DELETE</code> leaves its index entries behind for <code>VACUUM</code> to clean up later — but they are exceptions, not the default.</p>\n<p>So every index is a trade: you buy read speed with write cost. Inserting a single row into a table with five indexes means updating six structures at once. An index isn’t “free read speed,” it’s “read speed paid for with writes.”</p>\n<h2 id=\"a-missing-index-measure-dont-guess\">A missing index: measure, don’t guess</h2>\n<p>Find a missing index from the query plan, not from a hunch:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">EXPLAIN ANALYZE</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> *</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">WHERE</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> status</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> &#39;pending&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p>If you see a <code>Seq Scan</code> on a large table in the output and the query returns a small fraction of the rows, an index is probably missing. Scan the <code>pg_stat_user_tables</code> table for large tables with a high <code>seq_scan</code> count — those are your candidates.</p>\n<p>Add the index for a real, slow query. An index added “in case we need it later” is the database-layer version of <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-just-in-case-code/\">speculative generality</a>.</p>\n<h2 id=\"too-many-indexes-find-the-unused-ones\">Too many indexes: find the unused ones</h2>\n<p>In the other direction, indexes that are never used make every write more expensive for nothing. Find those by measurement too:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">SELECT</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> indexrelname, idx_scan</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">FROM</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> pg_stat_user_indexes</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">WHERE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> idx_scan </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> 0</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span></code></pre>\n<p>An index with <code>idx_scan = 0</code> means it’s speeding up no reads at all but adding cost to every write. (Keep the indexes for primary keys and unique constraints, of course.) This is the first cleanup listed at the write breaking point of <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a>.</p>\n<h2 id=\"how-do-you-choose-the-right-index\">How do you choose the right index?</h2>\n<p>An index isn’t just “present or absent”; choosing the right type and shape matters:</p>\n<ul>\n<li><strong>Column order in a composite index.</strong> An <code>(a, b)</code> index serves equality on <code>a</code> + a range query on <code>b</code>; a lookup on <code>b</code> alone can still use the index, but it doesn’t narrow the portion that gets scanned — before PostgreSQL 18 the whole index is scanned, and from 18 on the skip scan optimization narrows it down. Put the column filtered by equality first, the one filtered by range last.</li>\n<li><strong>Partial index.</strong> If the query always looks at the same subset, limit the index to that subset too: <code>CREATE INDEX ... WHERE status = &#39;active&#39;</code>. A smaller index, cheaper maintenance.</li>\n<li><strong>Covering index.</strong> With <code>INCLUDE</code> you can add frequently read columns to the index and keep the database from going to the table at all.</li>\n<li><strong>Non-B-tree types.</strong> B-tree for equality/ordering; GIN for <code>jsonb</code> and full text; small, cheap BRIN for purely ordered, append-heavy data.</li>\n</ul>\n<h2 id=\"duplicate-and-overlapping-indexes\">Duplicate and overlapping indexes</h2>\n<p>An index on <code>(a)</code> is redundant if you already have an <code>(a, b)</code> index — the composite index serves queries starting with <code>a</code> too. Clean up overlaps like these periodically; each one is a silent write tax.</p>\n<h2 id=\"balance-is-set-with-the-query-plan\">Balance is set with the query plan</h2>\n<p>One rule: don’t add an index by guesswork, and don’t drop one by guesswork either. An index is added because a real query plan asks for it; an index is dropped because the statistics show no one is using it. The balance between too few and too many is struck with <code>EXPLAIN ANALYZE</code> and <code>pg_stat_user_indexes</code>, not with gut feeling.</p>\n<hr/>\n<p>Index management starts with shedding the belief that “more indexes is better.” Every index is a read gain and a write cost; good management is keeping the two in balance by measuring them.</p>\n<p>A missing index slows the query; too many slow the whole table. Measurement guards against both.</p>",
      "content_text": "> **TL;DR:** An index is not free read speed; it is read speed paid for with writes. Every INSERT writes an entry into every index on the table, and an UPDATE does the same the moment it touches an indexed column. A HOT update and a partial index are the exceptions, not the default. So add an index because a real query plan asked for it, and drop one because pg_stat_user_indexes shows idx_scan = 0.\n\nI've seen two opposite teams. One had put no indexes on the table at all — every query a sequential scan, every list page taking seconds. The other had done the exact opposite: \"just in case,\" it had created an index on every column, and now every `INSERT` crawled along.\n\nBoth are two ends of the same fallacy: thinking an index is a free source of speed.\n\n## An index is not free speed\n\nAn index speeds up reads, because instead of scanning the whole table the database looks at an ordered structure. But that ordered structure doesn't stay current on its own: an `INSERT` writes an entry into **every index** on the table, and an `UPDATE` does the same as soon as it touches an indexed column. There are exceptions — a HOT update that changes no indexed column leaves the indexes alone, a partial index is skipped for rows outside its `WHERE` clause, and a `DELETE` leaves its index entries behind for `VACUUM` to clean up later — but they are exceptions, not the default.\n\nSo every index is a trade: you buy read speed with write cost. Inserting a single row into a table with five indexes means updating six structures at once. An index isn't \"free read speed,\" it's \"read speed paid for with writes.\"\n\n## A missing index: measure, don't guess\n\nFind a missing index from the query plan, not from a hunch:\n\n```sql\nEXPLAIN ANALYZE\nSELECT * FROM orders WHERE status = 'pending';\n```\n\nIf you see a `Seq Scan` on a large table in the output and the query returns a small fraction of the rows, an index is probably missing. Scan the `pg_stat_user_tables` table for large tables with a high `seq_scan` count — those are your candidates.\n\nAdd the index for a real, slow query. An index added \"in case we need it later\" is the database-layer version of [speculative generality](/engineering/essays/the-cost-of-just-in-case-code/).\n\n## Too many indexes: find the unused ones\n\nIn the other direction, indexes that are never used make every write more expensive for nothing. Find those by measurement too:\n\n```sql\nSELECT indexrelname, idx_scan\nFROM pg_stat_user_indexes\nWHERE idx_scan = 0;\n```\n\nAn index with `idx_scan = 0` means it's speeding up no reads at all but adding cost to every write. (Keep the indexes for primary keys and unique constraints, of course.) This is the first cleanup listed at the write breaking point of [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/).\n\n## How do you choose the right index?\n\nAn index isn't just \"present or absent\"; choosing the right type and shape matters:\n\n- **Column order in a composite index.** An `(a, b)` index serves equality on `a` + a range query on `b`; a lookup on `b` alone can still use the index, but it doesn't narrow the portion that gets scanned — before PostgreSQL 18 the whole index is scanned, and from 18 on the skip scan optimization narrows it down. Put the column filtered by equality first, the one filtered by range last.\n- **Partial index.** If the query always looks at the same subset, limit the index to that subset too: `CREATE INDEX ... WHERE status = 'active'`. A smaller index, cheaper maintenance.\n- **Covering index.** With `INCLUDE` you can add frequently read columns to the index and keep the database from going to the table at all.\n- **Non-B-tree types.** B-tree for equality/ordering; GIN for `jsonb` and full text; small, cheap BRIN for purely ordered, append-heavy data.\n\n## Duplicate and overlapping indexes\n\nAn index on `(a)` is redundant if you already have an `(a, b)` index — the composite index serves queries starting with `a` too. Clean up overlaps like these periodically; each one is a silent write tax.\n\n## Balance is set with the query plan\n\nOne rule: don't add an index by guesswork, and don't drop one by guesswork either. An index is added because a real query plan asks for it; an index is dropped because the statistics show no one is using it. The balance between too few and too many is struck with `EXPLAIN ANALYZE` and `pg_stat_user_indexes`, not with gut feeling.\n\n---\n\nIndex management starts with shedding the belief that \"more indexes is better.\" Every index is a read gain and a write cost; good management is keeping the two in balance by measuring them.\n\nA missing index slows the query; too many slow the whole table. Measurement guards against both.\n\n## Sources\n\n- [CREATE INDEX: CONCURRENTLY, INCLUDE, partial indexes and index methods](https://www.postgresql.org/docs/current/sql-createindex.html) — PostgreSQL\n- [Multicolumn Indexes: column order and the skip scan optimization](https://www.postgresql.org/docs/current/indexes-multicolumn.html) — PostgreSQL\n- [PostgreSQL 18 Release Notes: allow skip scans of btree indexes](https://www.postgresql.org/docs/release/18.0/) — PostgreSQL\n- [Heap-Only Tuples (HOT)](https://www.postgresql.org/docs/current/storage-hot.html) — PostgreSQL\n\n## Frequently asked\n\n### Does every INSERT have to update every index on the table?\n\nFor an INSERT, yes: the new row gets an entry in every index. An UPDATE is different. A HOT update that changes no indexed column leaves the indexes alone, and a partial index is skipped for rows outside its WHERE clause. A DELETE leaves its index entries behind for VACUUM to clean up later.\n\n### How do you find indexes nobody uses?\n\nQuery pg_stat_user_indexes for idx_scan = 0. Those indexes speed up no reads at all while adding cost to every write. Keep the indexes backing primary keys and unique constraints regardless.",
      "date_published": "2026-09-05T00:00:00.000Z",
      "date_modified": "2026-09-06T00:00:00.000Z",
      "tags": [
        "postgresql",
        "database",
        "performance",
        "indexing",
        "PostgreSQL in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/zero-downtime-database-migrations/",
      "url": "https://muhammetsafak.com/engineering/notes/zero-downtime-database-migrations/",
      "title": "Changing Schema in Production With Zero Downtime",
      "summary": "A schema change is not what is dangerous; doing it in one step is. Only operations taking an ACCESS EXCLUSIVE lock queue up reads as well as writes, and on a fifty-million-row table that queue is the outage. Break the change into expand-contract steps: add the constraint NOT VALID and run VALIDATE separately, build indexes CONCURRENTLY, and give the migration session a short lock_timeout.",
      "content_html": "<p>A deploy ran a single <code>ALTER TABLE</code> on a table with 50 million rows and locked it for four minutes. For four minutes, every request that touched that table waited; the site was effectively down. The migration itself was correct — the problem was doing it in one step.</p>\n<p>The dangerous thing is not the schema change. The dangerous thing is making a schema change all at once, without thinking about backward compatibility.</p>\n<h2 id=\"who-takes-the-lock\">Who takes the lock?</h2>\n<p>Not every schema change costs the same. In modern PostgreSQL, adding a column with a constant <code>DEFAULT</code> is a metadata operation — it’s fast. The real danger is in operations that lock the table for a long time:</p>\n<ul>\n<li><code>CREATE INDEX</code> — without <code>CONCURRENTLY</code>, it closes the table to writes.</li>\n<li><code>ALTER COLUMN ... TYPE</code> changes that rewrite the table.</li>\n<li><code>NOT NULL</code>, <code>CHECK</code>, or foreign key additions that scan the whole table.</li>\n</ul>\n<p>These operations take a strong lock; the ones that take it in <code>ACCESS EXCLUSIVE</code> mode — a table rewrite, or adding <code>NOT NULL</code>/<code>CHECK</code> — queue up every query touching the table, reads included. The rest block writes only. If the table is large, the queue grows.</p>\n<h2 id=\"the-dangerous-part-is-the-single-step\">The dangerous part is the single step</h2>\n<p>The solution is not to avoid migrations; it’s to break every dangerous migration into small steps, each of which is safe and backward-compatible on its own. This is called the <strong>expand-contract</strong> pattern.</p>\n<p>Suppose you want to rename a column. A single-step <code>RENAME COLUMN</code> instantly breaks running code that reads the old column. Instead, <span data-scheduled=\"/engineering/systems/zero-downtime-deployment/\">three deploys</span>:</p>\n<ol>\n<li><strong>Expand.</strong> Add the new column. Have the code write to both old and new, still reading from old.</li>\n<li><strong>Migrate.</strong> Move the old data into the new column in batches. Now have the code read from new.</li>\n<li><strong>Contract.</strong> Drop the old column.</li>\n</ol>\n<p>Each step works with both the code from the previous release and the new code. At no moment is the running code incompatible with the schema.</p>\n<h2 id=\"safe-recipes\">Safe recipes</h2>\n<p>The zero-downtime versions of common changes:</p>\n<p><strong>A new <code>NOT NULL</code> column.</strong> Adding <code>NOT NULL</code> in one step scans the table. Split it:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#6A737D;--shiki-dark:#6A737D\">-- 1. Add it as nullable first</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">ALTER</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> TABLE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">ADD</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> COLUMN </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">status</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> text</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">;</span></span>\n<span class=\"line\"></span>\n<span class=\"line\"><span style=\"color:#6A737D;--shiki-dark:#6A737D\">-- 2. Backfill existing rows in batches (on the application side)</span></span>\n<span class=\"line\"></span>\n<span class=\"line\"><span style=\"color:#6A737D;--shiki-dark:#6A737D\">-- 3. Add the constraint NOT VALID first, then validate in a separate step</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">ALTER</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> TABLE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">ADD</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> CONSTRAINT</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders_status_not_null</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">    CHECK</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> (</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">status</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> IS NOT NULL</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">) </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">NOT</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> VALID;</span></span>\n<span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">ALTER</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> TABLE</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders VALIDATE </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">CONSTRAINT</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders_status_not_null;</span></span></code></pre>\n<p>A constraint added with <code>NOT VALID</code> applies immediately to new rows but does not scan existing ones; <code>VALIDATE</code> then scans the table with only a <code>SHARE UPDATE EXCLUSIVE</code> lock — it doesn’t block writes.</p>\n<p><strong><a href=\"https://muhammetsafak.com/engineering/notes/index-management/\">An index</a>.</strong> Always <code>CONCURRENTLY</code>:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"sql\"><code><span class=\"line\"><span style=\"color:#D73A49;--shiki-dark:#F97583\">CREATE</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> INDEX</span><span style=\"color:#6F42C1;--shiki-dark:#B392F0\"> CONCURRENTLY</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> idx_orders_status </span><span style=\"color:#D73A49;--shiki-dark:#F97583\">ON</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> orders (</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">status</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">);</span></span></code></pre>\n<p><strong>A foreign key.</strong> The same two-step pattern: first <code>ADD CONSTRAINT ... NOT VALID</code>, then <code>VALIDATE CONSTRAINT</code>.</p>\n<p><strong><code>lock_timeout</code>.</strong> While a migration waits for a lock behind a long-running query, it blocks everything behind it too. To prevent this, give the migration session a short <code>lock_timeout</code> — if the lock can’t be taken immediately, let the migration fail instead of waiting, and retry it yourself.</p>\n<blockquote><p><strong>Tan:</strong> Expand-contract is paid for in calendar time: a change like the rename example is spread over three deploys. If the contract step is forgotten, the old column becomes permanent. Opening that step as its own ticket on the same day as the expand step keeps the cost from turning into debt.</p></blockquote>\n<h2 id=\"code-and-schema-must-be-compatible-together\">Code and schema must be compatible together</h2>\n<p>The essence of expand-contract is one rule: at every intermediate step, both the <strong>old code still running</strong> and the <strong>new code</strong> must be able to work with the current schema.</p>\n<p>The database schema is what I called a “one-way door” in <a href=\"https://muhammetsafak.com/engineering/essays/the-cost-of-just-in-case-code/\">the cost of just-in-case code</a> — rolling it back is expensive. So design the change not as one big, irreversible step, but as small steps that can each be rolled back individually.</p>\n<hr/>\n<p>Zero-downtime migration is not a tool but a discipline: breaking every schema change into steps small enough that the running code never notices.</p>\n<p>The dangerous thing is not the change itself, but doing it in one breath.</p>",
      "content_text": "> **TL;DR:** A schema change is not what is dangerous; doing it in one step is. Only operations taking an ACCESS EXCLUSIVE lock queue up reads as well as writes, and on a fifty-million-row table that queue is the outage. Break the change into expand-contract steps: add the constraint NOT VALID and run VALIDATE separately, build indexes CONCURRENTLY, and give the migration session a short lock_timeout.\n\nA deploy ran a single `ALTER TABLE` on a table with 50 million rows and locked it for four minutes. For four minutes, every request that touched that table waited; the site was effectively down. The migration itself was correct — the problem was doing it in one step.\n\nThe dangerous thing is not the schema change. The dangerous thing is making a schema change all at once, without thinking about backward compatibility.\n\n## Who takes the lock?\n\nNot every schema change costs the same. In modern PostgreSQL, adding a column with a constant `DEFAULT` is a metadata operation — it's fast. The real danger is in operations that lock the table for a long time:\n\n- `CREATE INDEX` — without `CONCURRENTLY`, it closes the table to writes.\n- `ALTER COLUMN ... TYPE` changes that rewrite the table.\n- `NOT NULL`, `CHECK`, or foreign key additions that scan the whole table.\n\nThese operations take a strong lock; the ones that take it in `ACCESS EXCLUSIVE` mode — a table rewrite, or adding `NOT NULL`/`CHECK` — queue up every query touching the table, reads included. The rest block writes only. If the table is large, the queue grows.\n\n## The dangerous part is the single step\n\nThe solution is not to avoid migrations; it's to break every dangerous migration into small steps, each of which is safe and backward-compatible on its own. This is called the **expand-contract** pattern.\n\nSuppose you want to rename a column. A single-step `RENAME COLUMN` instantly breaks running code that reads the old column. Instead, three deploys:\n\n1. **Expand.** Add the new column. Have the code write to both old and new, still reading from old.\n2. **Migrate.** Move the old data into the new column in batches. Now have the code read from new.\n3. **Contract.** Drop the old column.\n\nEach step works with both the code from the previous release and the new code. At no moment is the running code incompatible with the schema.\n\n## Safe recipes\n\nThe zero-downtime versions of common changes:\n\n**A new `NOT NULL` column.** Adding `NOT NULL` in one step scans the table. Split it:\n\n```sql\n-- 1. Add it as nullable first\nALTER TABLE orders ADD COLUMN status text;\n\n-- 2. Backfill existing rows in batches (on the application side)\n\n-- 3. Add the constraint NOT VALID first, then validate in a separate step\nALTER TABLE orders ADD CONSTRAINT orders_status_not_null\n    CHECK (status IS NOT NULL) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_status_not_null;\n```\n\nA constraint added with `NOT VALID` applies immediately to new rows but does not scan existing ones; `VALIDATE` then scans the table with only a `SHARE UPDATE EXCLUSIVE` lock — it doesn't block writes.\n\n**[An index](/engineering/notes/index-management/).** Always `CONCURRENTLY`:\n\n```sql\nCREATE INDEX CONCURRENTLY idx_orders_status ON orders (status);\n```\n\n**A foreign key.** The same two-step pattern: first `ADD CONSTRAINT ... NOT VALID`, then `VALIDATE CONSTRAINT`.\n\n**`lock_timeout`.** While a migration waits for a lock behind a long-running query, it blocks everything behind it too. To prevent this, give the migration session a short `lock_timeout` — if the lock can't be taken immediately, let the migration fail instead of waiting, and retry it yourself.\n\n\n> **Tan:** Expand-contract is paid for in calendar time: a change like the rename example is spread over three deploys. If the contract step is forgotten, the old column becomes permanent. Opening that step as its own ticket on the same day as the expand step keeps the cost from turning into debt.\n\n\n## Code and schema must be compatible together\n\nThe essence of expand-contract is one rule: at every intermediate step, both the **old code still running** and the **new code** must be able to work with the current schema.\n\nThe database schema is what I called a \"one-way door\" in [the cost of just-in-case code](/engineering/essays/the-cost-of-just-in-case-code/) — rolling it back is expensive. So design the change not as one big, irreversible step, but as small steps that can each be rolled back individually.\n\n---\n\nZero-downtime migration is not a tool but a discipline: breaking every schema change into steps small enough that the running code never notices.\n\nThe dangerous thing is not the change itself, but doing it in one breath.\n\n## Steps\n\n**Changing a column without downtime, using expand–contract** — Running migrations without causing downtime in production: backward-compatible steps, multi-phase column changes, and avoiding table locks\n\n1. **Expand** — Add the new column. Have the code write to both old and new, still reading from old.\n2. **Migrate** — Move the old data into the new column in batches; once it is moved, have the code read from new.\n3. **Contract** — Drop the old column. Every step works with both the previous release’s code and the new code, so the running code is never incompatible with the schema.\n\n## Sources\n\n- [ALTER TABLE: NOT VALID constraints, VALIDATE CONSTRAINT and ADD COLUMN with a DEFAULT](https://www.postgresql.org/docs/current/sql-altertable.html) — PostgreSQL\n- [Explicit Locking: table-level lock modes](https://www.postgresql.org/docs/current/explicit-locking.html) — PostgreSQL\n- [CREATE INDEX: building indexes concurrently](https://www.postgresql.org/docs/current/sql-createindex.html) — PostgreSQL\n- [Client Connection Defaults: lock_timeout](https://www.postgresql.org/docs/current/runtime-config-client.html) — PostgreSQL\n\n## Frequently asked\n\n### Which schema changes block reads and not just writes?\n\nThe ones that take an ACCESS EXCLUSIVE lock: a table rewrite, or adding NOT NULL or CHECK. Only that lock mode conflicts with a plain SELECT. A CREATE INDEX without CONCURRENTLY takes a weaker lock that closes the table to writes but lets reads through.\n\n### Why add a constraint NOT VALID first and validate it in a separate step?\n\nA constraint added with NOT VALID applies to new rows immediately without scanning the table, so it commits at once. The separate VALIDATE CONSTRAINT step then scans the table holding only a SHARE UPDATE EXCLUSIVE lock, which does not block writes.",
      "date_published": "2026-08-29T00:00:00.000Z",
      "date_modified": "2026-09-30T00:00:00.000Z",
      "tags": [
        "postgresql",
        "database",
        "migrations",
        "production",
        "PostgreSQL in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/read-write-splitting/",
      "url": "https://muhammetsafak.com/engineering/notes/read-write-splitting/",
      "title": "Read/Write Splitting: Separating Read and Write Load",
      "summary": "A read replica scales reads and adds nothing to write capacity, so the trade is not free: the price is replication lag. Laravel's sticky option repairs read-after-write only inside a single request; across two requests the user still sees the profile they just updated as stale. Do index discipline first, because a replica is often an expensive way to buy what one CREATE INDEX would have solved.",
      "content_html": "<p>The primary database’s CPU was constantly maxed out. The interesting part: the write rate was low. Almost all of the load was reads — report pages, listing endpoints, search. A single primary was trying to carry a pile of reads that never needed it in the first place.</p>\n<p>Separating read and write load — read/write splitting — is the known fix for this picture. But applied at the wrong time, or without awareness of the right traps, it brings more problems than it solves. Separating the read and write <em>model</em> is a different decision; <a href=\"https://muhammetsafak.com/engineering/notes/when-is-cqrs-necessary/\">CQRS</a> and a read replica are not the same thing.</p>\n<h2 id=\"most-load-is-read-heavy\">Most load is read-heavy</h2>\n<p>How read-heavy the traffic is depends on the workload: in measurements of the standard OLTP benchmarks, TPC-E runs 90.69% reads while TPC-C stays at 65.71% — so measure your own ratio instead of assuming it. Every order is written once but read dozens of times: in the list, in the detail view, in a report, on a dashboard. This asymmetry is what makes read/write splitting appealing — because the side you need to scale is obvious.</p>\n<h2 id=\"first-is-this-really-a-capacity-problem\">First: is this really a capacity problem?</h2>\n<p>Stop before adding a replica. A full primary doesn’t always mean “out of capacity.” Often a single missing index makes the primary look many times busier than it is.</p>\n<p>Adding a replica — a new server, replication setup, lag monitoring — can amount to expensively buying your way out of a problem a single <code>CREATE INDEX</code> would have solved. The order in <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">the breaking points of data-intensive systems</a> is clear: index discipline first, then replicas. Don’t skip that order.</p>\n<p>Measure your queries with <code>EXPLAIN ANALYZE</code>. If the primary is genuinely saturating under correctly indexed queries — that’s when you reach for a replica.</p>\n<h2 id=\"a-replica-scales-reads-not-writes\">A replica scales reads, not writes</h2>\n<p>Let’s be clear: a read replica adds <strong>nothing</strong> to your write capacity. The same writes are replayed on every replica. A replica solves a read-load problem; if you have a write-load problem, a replica is the wrong tool.</p>\n<h2 id=\"setting-it-up-in-laravel\">Setting it up in Laravel</h2>\n<p>Laravel supports read/write connection splitting natively:</p>\n<pre class=\"astro-code astro-code-themes github-light github-dark\" style=\"background-color:#fff;--shiki-dark-bg:#24292e;color:#24292e;--shiki-dark:#e1e4e8;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word\" tabindex=\"0\" data-language=\"php\"><code><span class=\"line\"><span style=\"color:#6A737D;--shiki-dark:#6A737D\">// config/database.php</span></span>\n<span class=\"line\"><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;pgsql&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =&gt;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> [</span></span>\n<span class=\"line\"><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">    &#39;driver&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =&gt;</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\"> &#39;pgsql&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">    &#39;read&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">   =&gt;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> [</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;host&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =&gt;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> [</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;10.0.0.2&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">]],   </span><span style=\"color:#6A737D;--shiki-dark:#6A737D\">// replica</span></span>\n<span class=\"line\"><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">    &#39;write&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\">  =&gt;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> [</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;host&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =&gt;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\"> [</span><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">&#39;10.0.0.1&#39;</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">]],   </span><span style=\"color:#6A737D;--shiki-dark:#6A737D\">// primary</span></span>\n<span class=\"line\"><span style=\"color:#032F62;--shiki-dark:#9ECBFF\">    &#39;sticky&#39;</span><span style=\"color:#D73A49;--shiki-dark:#F97583\"> =&gt;</span><span style=\"color:#005CC5;--shiki-dark:#79B8FF\"> true</span><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"color:#6A737D;--shiki-dark:#6A737D\">    // ...shared settings</span></span>\n<span class=\"line\"><span style=\"color:#24292E;--shiki-dark:#E1E4E8\">],</span></span></code></pre>\n<p><code>SELECT</code>s go to the replica, <code>INSERT/UPDATE/DELETE</code>s go to the primary. The replica gets its own connection pool — separate from the primary’s; if you use <a href=\"https://muhammetsafak.com/engineering/notes/pgbouncer-auth-query/\">pgBouncer</a>, they are two distinct pools.</p>\n<h2 id=\"replication-lag-the-real-bill\">Replication lag: the real bill</h2>\n<p>The replica trails the primary by a few milliseconds — a few seconds under load. This delay is the real cost of read/write splitting, and its name is the <strong>read-after-write</strong> problem.</p>\n<p><code>sticky =&gt; true</code> partly addresses it: if you wrote within a request, the subsequent reads in that same request go to the primary. But <code>sticky</code> only works within the boundary of <strong>a single request</strong>.</p>\n<p>Outside that boundary it’s still open: a user updates their profile (request 1, written to the primary), moves to the next page (request 2, read from the replica), and sees their old profile, not yet replayed on the replica. The user sees their own data as stale. This looks like a bug, but it’s actually a tradeoff the architecture accepts — one that has to be accepted deliberately.</p>\n<h2 id=\"the-query-classification-discipline\">The query classification discipline</h2>\n<p>Setting up read/write splitting requires every read to answer one question: <strong>can this query read stale data?</strong></p>\n<ul>\n<li><strong>Can read from a replica:</strong> lists, reports, search results, dashboards. A few seconds of delay is irrelevant.</li>\n<li><strong>Must read from the primary:</strong> account balance, stock count, authorization checks, any read a write decision depends on.</li>\n</ul>\n<p>This classification is now part of the architecture, and it needs to be documented. A new developer must have somewhere to look for “where should this query read from” — otherwise the classification quietly rots.</p>\n<h2 id=\"when-do-you-actually-need-it\">When do you actually need it?</h2>\n<p>Read/write splitting is the right move when these three conditions hold together:</p>\n<ol>\n<li>Index discipline is complete; queries are correctly indexed and the primary is still saturating.</li>\n<li>The load is measurably read-heavy.</li>\n<li>There’s the discipline to do and document the stale-read classification.</li>\n</ol>\n<p>If any one of these is missing, deferring the replica is cheaper.</p>\n<hr/>\n<p>Read/write splitting is a cheaper scaling move than growing vertically — but it isn’t free. The price is replication lag, and the cost of ignoring it is paid by showing users their own data as stale.</p>\n<p>Before splitting reads, know which reads can tolerate staleness.</p>",
      "content_text": "> **TL;DR:** A read replica scales reads and adds nothing to write capacity, so the trade is not free: the price is replication lag. Laravel's sticky option repairs read-after-write only inside a single request; across two requests the user still sees the profile they just updated as stale. Do index discipline first, because a replica is often an expensive way to buy what one CREATE INDEX would have solved.\n\nThe primary database's CPU was constantly maxed out. The interesting part: the write rate was low. Almost all of the load was reads — report pages, listing endpoints, search. A single primary was trying to carry a pile of reads that never needed it in the first place.\n\nSeparating read and write load — read/write splitting — is the known fix for this picture. But applied at the wrong time, or without awareness of the right traps, it brings more problems than it solves. Separating the read and write *model* is a different decision; [CQRS](/engineering/notes/when-is-cqrs-necessary/) and a read replica are not the same thing.\n\n## Most load is read-heavy\n\nHow read-heavy the traffic is depends on the workload: in measurements of the standard OLTP benchmarks, TPC-E runs 90.69% reads while TPC-C stays at 65.71% — so measure your own ratio instead of assuming it. Every order is written once but read dozens of times: in the list, in the detail view, in a report, on a dashboard. This asymmetry is what makes read/write splitting appealing — because the side you need to scale is obvious.\n\n## First: is this really a capacity problem?\n\nStop before adding a replica. A full primary doesn't always mean \"out of capacity.\" Often a single missing index makes the primary look many times busier than it is.\n\nAdding a replica — a new server, replication setup, lag monitoring — can amount to expensively buying your way out of a problem a single `CREATE INDEX` would have solved. The order in [the breaking points of data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/) is clear: index discipline first, then replicas. Don't skip that order.\n\nMeasure your queries with `EXPLAIN ANALYZE`. If the primary is genuinely saturating under correctly indexed queries — that's when you reach for a replica.\n\n## A replica scales reads, not writes\n\nLet's be clear: a read replica adds **nothing** to your write capacity. The same writes are replayed on every replica. A replica solves a read-load problem; if you have a write-load problem, a replica is the wrong tool.\n\n## Setting it up in Laravel\n\nLaravel supports read/write connection splitting natively:\n\n```php\n// config/database.php\n'pgsql' => [\n    'driver' => 'pgsql',\n    'read'   => ['host' => ['10.0.0.2']],   // replica\n    'write'  => ['host' => ['10.0.0.1']],   // primary\n    'sticky' => true,\n    // ...shared settings\n],\n```\n\n`SELECT`s go to the replica, `INSERT/UPDATE/DELETE`s go to the primary. The replica gets its own connection pool — separate from the primary's; if you use [pgBouncer](/engineering/notes/pgbouncer-auth-query/), they are two distinct pools.\n\n## Replication lag: the real bill\n\nThe replica trails the primary by a few milliseconds — a few seconds under load. This delay is the real cost of read/write splitting, and its name is the **read-after-write** problem.\n\n`sticky => true` partly addresses it: if you wrote within a request, the subsequent reads in that same request go to the primary. But `sticky` only works within the boundary of **a single request**.\n\nOutside that boundary it's still open: a user updates their profile (request 1, written to the primary), moves to the next page (request 2, read from the replica), and sees their old profile, not yet replayed on the replica. The user sees their own data as stale. This looks like a bug, but it's actually a tradeoff the architecture accepts — one that has to be accepted deliberately.\n\n## The query classification discipline\n\nSetting up read/write splitting requires every read to answer one question: **can this query read stale data?**\n\n- **Can read from a replica:** lists, reports, search results, dashboards. A few seconds of delay is irrelevant.\n- **Must read from the primary:** account balance, stock count, authorization checks, any read a write decision depends on.\n\nThis classification is now part of the architecture, and it needs to be documented. A new developer must have somewhere to look for \"where should this query read from\" — otherwise the classification quietly rots.\n\n## When do you actually need it?\n\nRead/write splitting is the right move when these three conditions hold together:\n\n1. Index discipline is complete; queries are correctly indexed and the primary is still saturating.\n2. The load is measurably read-heavy.\n3. There's the discipline to do and document the stale-read classification.\n\nIf any one of these is missing, deferring the replica is cheaper.\n\n---\n\nRead/write splitting is a cheaper scaling move than growing vertically — but it isn't free. The price is replication lag, and the cost of ignoring it is paid by showing users their own data as stale.\n\nBefore splitting reads, know which reads can tolerate staleness.\n\n## Sources\n\n- [Log-Shipping Standby Servers: streaming replication and hot standby](https://www.postgresql.org/docs/current/warm-standby.html) — PostgreSQL\n- [TPC-E vs. TPC-C: Characterizing the New TPC-E Benchmark via an I/O Comparison Study](https://www.cs.cmu.edu/~chensm/papers/TPCE-sigmod-record10.pdf) — ACM SIGMOD Record 39(3), 2010\n- [Database: Read and Write Connections](https://laravel.com/docs/12.x/database#read-and-write-connections) — Laravel\n\n## Frequently asked\n\n### Does adding a read replica increase write capacity?\n\nNo. The same writes are replayed on every replica, so a replica adds nothing to write throughput. It solves a read-load problem; if the problem is on the write side, a replica is the wrong tool.\n\n### What does the sticky option solve, and what does it not?\n\nWith sticky enabled, reads that follow a write within the same request go to the primary, so a user never reads their own write as stale inside one request. It does nothing across requests: the next page can still read from a replica that has not replayed the write yet.",
      "date_published": "2026-08-22T00:00:00.000Z",
      "date_modified": "2026-10-07T00:00:00.000Z",
      "tags": [
        "postgresql",
        "database",
        "scaling",
        "performance",
        "PostgreSQL in Production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/notes/the-right-cache-strategy/",
      "url": "https://muhammetsafak.com/engineering/notes/the-right-cache-strategy/",
      "title": "Before You Reach for Redis: The Right Cache Strategy",
      "summary": "A cache is never a faster database; it is speed bought with accepted staleness, so the first question is not technical: how stale may this data be? TTL is the boring default, because it does not require knowing every write path and it does not break silently when one is forgotten. Explicit invalidation is exact only if you catch every path. And a cache reduces read load, never write load.",
      "content_html": "<p>A team added a Redis cache because “the site is slow.” A week later the support queue filled up: “I updated the price but the old one still shows.” The cache had fixed the slowness — and quietly created a new problem.</p>\n<p>Adding a cache is not a free performance win. It trades freshness for speed; and if you didn’t make that trade deliberately, the bill comes back as a bug.</p>\n<h2 id=\"a-cache-is-a-consistency-concession\">A cache is a consistency concession</h2>\n<p>The moment you cache a value, you’ve accepted this: someone, for a while, may see stale data. A cache is never a “faster database”; it’s “speed in exchange for accepted staleness.”</p>\n<p>So the first question isn’t technical: <strong>how stale can this data be?</strong> Data whose answer is “not at all” — an account balance, a stock count — should be thought through twice before it’s cached.</p>\n<h2 id=\"questions-to-ask-first\">Questions to ask first</h2>\n<p>Before you turn on Redis:</p>\n<ul>\n<li><strong>Is this really a read bottleneck?</strong> “The site is slow” is a hypothesis, not a measurement. Adding a cache without seeing the source of the slowness is covering up something you don’t understand.</li>\n<li><strong>Is the slowness actually a missing index?</strong> A cache papers over a bad query but doesn’t fix it. Hiding behind a cache what a <code>CREATE INDEX</code> would solve is moving the problem, not solving it — this is exactly the wrong breaking point in <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a>.</li>\n<li><strong>How stale can this data stay?</strong> The answer determines which strategy you pick.</li>\n</ul>\n<h2 id=\"why-is-invalidation-hard\">Why is invalidation hard?</h2>\n<p>Cache invalidation gets cited as one of the two hard problems in software — and that’s no exaggeration. Putting the cache in is easy; <strong>clearing</strong> it at the right moment is hard.</p>\n<p>Because a cached value must be cleared on every write path that affects it. A product price changes not only from the “edit product” screen; it also changes from a bulk price update, a discount job, an admin script. Finding <strong>all</strong> of those paths and clearing the cache — that’s the hard part. Miss one, and you get the support ticket from the top of this post.</p>\n<h2 id=\"two-strategies\">Two strategies</h2>\n<p>In practice there are two roads:</p>\n<ul>\n<li><strong>TTL-based.</strong> You assign the value a lifetime — 60 seconds, 5 minutes. When it expires, the cache refreshes itself. Simple, sturdy, and it doesn’t require knowing every write path. In return: you accept staleness up to the TTL.</li>\n<li><strong>Explicit invalidation.</strong> You delete the cache by hand when the data changes. Exact and fresh — but only if you catch every write path completely.</li>\n</ul>\n<p>My default is TTL. It’s boring, predictable, and it doesn’t break silently because of a forgotten write path. I move to explicit invalidation only when staleness is genuinely unacceptable and the number of write paths is limited and known. Most of the time the two are used together: a short TTL as a safety net, explicit invalidation for speed.</p>\n<h2 id=\"a-cache-doesnt-reduce-writes\">A cache doesn’t reduce writes</h2>\n<p>A common mistake: trying to rescue a system under write load by adding a cache. A cache reduces <strong>read</strong> load; it has no effect on write load — if anything, invalidation itself is extra write work. If your problem is on the write side, a cache is the wrong tool.</p>\n<blockquote><p><strong>Tan:</strong> The staleness window should not be an engineer’s solo pick. How long a customer may see the old price after an update is a question for the product side to answer. Get that answer in writing: a sentence like “an update shows up within this long” is the contract you can point to before the support queue fills up.</p></blockquote>\n<h2 id=\"practical-patterns\">Practical patterns</h2>\n<ul>\n<li><strong>Cache-aside.</strong> Read: check the cache first, and on a miss fetch the value from the database and write it to the cache. The most common and most understandable pattern.</li>\n<li><strong>Stampede protection.</strong> The instant a popular key’s TTL expires, hundreds of requests hit the database at once. On a cache miss, use a short lock so only one request goes to the database.</li>\n<li><strong>Key discipline.</strong> Namespace your cache keys — the pattern in the <a href=\"https://muhammetsafak.com/engineering/notes/shared-redis-namespace-isolation/\">shared Redis namespace isolation</a> note applies to cache keys too.</li>\n</ul>\n<hr/>\n<p>A cache is not the cure for a slow system; it’s the relief of a measured read bottleneck, bought with a deliberate consistency concession. A cache added without an invalidation plan takes back more as debt than it speeds up.</p>\n<p>Before you add a cache, ask: how old can this data be — and who’s going to clear it?</p>",
      "content_text": "> **TL;DR:** A cache is never a faster database; it is speed bought with accepted staleness, so the first question is not technical: how stale may this data be? TTL is the boring default, because it does not require knowing every write path and it does not break silently when one is forgotten. Explicit invalidation is exact only if you catch every path. And a cache reduces read load, never write load.\n\nA team added a Redis cache because \"the site is slow.\" A week later the support queue filled up: \"I updated the price but the old one still shows.\" The cache had fixed the slowness — and quietly created a new problem.\n\nAdding a cache is not a free performance win. It trades freshness for speed; and if you didn't make that trade deliberately, the bill comes back as a bug.\n\n## A cache is a consistency concession\n\nThe moment you cache a value, you've accepted this: someone, for a while, may see stale data. A cache is never a \"faster database\"; it's \"speed in exchange for accepted staleness.\"\n\nSo the first question isn't technical: **how stale can this data be?** Data whose answer is \"not at all\" — an account balance, a stock count — should be thought through twice before it's cached.\n\n## Questions to ask first\n\nBefore you turn on Redis:\n\n- **Is this really a read bottleneck?** \"The site is slow\" is a hypothesis, not a measurement. Adding a cache without seeing the source of the slowness is covering up something you don't understand.\n- **Is the slowness actually a missing index?** A cache papers over a bad query but doesn't fix it. Hiding behind a cache what a `CREATE INDEX` would solve is moving the problem, not solving it — this is exactly the wrong breaking point in [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/).\n- **How stale can this data stay?** The answer determines which strategy you pick.\n\n## Why is invalidation hard?\n\nCache invalidation gets cited as one of the two hard problems in software — and that's no exaggeration. Putting the cache in is easy; **clearing** it at the right moment is hard.\n\nBecause a cached value must be cleared on every write path that affects it. A product price changes not only from the \"edit product\" screen; it also changes from a bulk price update, a discount job, an admin script. Finding **all** of those paths and clearing the cache — that's the hard part. Miss one, and you get the support ticket from the top of this post.\n\n## Two strategies\n\nIn practice there are two roads:\n\n- **TTL-based.** You assign the value a lifetime — 60 seconds, 5 minutes. When it expires, the cache refreshes itself. Simple, sturdy, and it doesn't require knowing every write path. In return: you accept staleness up to the TTL.\n- **Explicit invalidation.** You delete the cache by hand when the data changes. Exact and fresh — but only if you catch every write path completely.\n\nMy default is TTL. It's boring, predictable, and it doesn't break silently because of a forgotten write path. I move to explicit invalidation only when staleness is genuinely unacceptable and the number of write paths is limited and known. Most of the time the two are used together: a short TTL as a safety net, explicit invalidation for speed.\n\n## A cache doesn't reduce writes\n\nA common mistake: trying to rescue a system under write load by adding a cache. A cache reduces **read** load; it has no effect on write load — if anything, invalidation itself is extra write work. If your problem is on the write side, a cache is the wrong tool.\n\n\n> **Tan:** The staleness window should not be an engineer’s solo pick. How long a customer may see the old price after an update is a question for the product side to answer. Get that answer in writing: a sentence like “an update shows up within this long” is the contract you can point to before the support queue fills up.\n\n\n## Practical patterns\n\n- **Cache-aside.** Read: check the cache first, and on a miss fetch the value from the database and write it to the cache. The most common and most understandable pattern.\n- **Stampede protection.** The instant a popular key's TTL expires, hundreds of requests hit the database at once. On a cache miss, use a short lock so only one request goes to the database.\n- **Key discipline.** Namespace your cache keys — the pattern in the [shared Redis namespace isolation](/engineering/notes/shared-redis-namespace-isolation/) note applies to cache keys too.\n\n---\n\nA cache is not the cure for a slow system; it's the relief of a measured read bottleneck, bought with a deliberate consistency concession. A cache added without an invalidation plan takes back more as debt than it speeds up.\n\nBefore you add a cache, ask: how old can this data be — and who's going to clear it?\n\n## Sources\n\n- [RFC 9111: HTTP Caching — freshness lifetime, stale responses and invalidation](https://www.rfc-editor.org/rfc/rfc9111.html) — IETF\n- [Distributed Locks with Redis](https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/) — Redis\n\n## Frequently asked\n\n### Should you use a TTL or explicit invalidation?\n\nTTL is the safer default: it needs no knowledge of every write path and it does not break silently when one is forgotten, at the price of accepting staleness up to the TTL. Move to explicit invalidation only when staleness is genuinely unacceptable and the write paths are limited and known. Most of the time both run together.\n\n### Does a cache reduce write load?\n\nNo. A cache reduces read load and has no effect on write load; invalidation itself is extra write work. If the problem is on the write side, a cache is the wrong tool.",
      "date_published": "2026-08-15T00:00:00.000Z",
      "date_modified": "2026-09-30T00:00:00.000Z",
      "tags": [
        "caching",
        "redis",
        "performance",
        "production"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    },
    {
      "id": "https://muhammetsafak.com/engineering/essays/the-nosql-trap/",
      "url": "https://muhammetsafak.com/engineering/essays/the-nosql-trap/",
      "title": "The NoSQL Trap: Starting Because \"It Has No Schema\"",
      "summary": "There is no such thing as schemaless data, only the question of where the shape is defined and who enforces it. Choosing a document database for the comfort of not wanting a schema does not delete the schema; it moves it into every read, every write and the team's heads, where nothing enforces it. NoSQL earns its place on horizontal write scale or genuinely heterogeneous documents, not on schema avoidance.",
      "content_html": "<p>I once saw a project that had picked MongoDB on the logic of “no schema, we’ll move fast” — two years later. Every read was defensive: <code>data?.user?.address?.city ?? null</code>. The reason was simple — no two documents had exactly the same shape. The schema hadn’t disappeared; it had just left the database and scattered across every bit of code that reads a document.</p>\n<h2 id=\"schemaless-is-a-misnomer\">“Schemaless” is a misnomer</h2>\n<p>There is no such thing as schemaless data. Data always has a shape: a user’s email, the line items of an order, the date on an invoice. The question is not whether there is a shape; it is <strong>where that shape is defined</strong>.</p>\n<p>There are two options. Either the schema lives in the database and is enforced by the database, or it lives in the application code and everyone is assumed to comply with it. Saying “schemaless” means choosing the second — not deleting the schema, but moving it somewhere it isn’t enforced.</p>\n<h2 id=\"where-does-the-schema-move\">Where does the schema move?</h2>\n<p>When the database stops enforcing the schema, that work doesn’t vanish; it scatters to these places:</p>\n<ul>\n<li><strong>To every read.</strong> The code can no longer assume the incoming document has the expected fields; it checks every field defensively.</li>\n<li><strong>To every write.</strong> There is no guarantee you wrote the right shape; there is only hope.</li>\n<li><strong>To scattered validation code.</strong> The <code>NOT NULL</code>, type check, and foreign key that the database does in a single line all turn into hand-written checks.</li>\n<li><strong>To the team’s heads.</strong> “That field is sometimes a string, sometimes an array” becomes undocumented tribal knowledge.</li>\n</ul>\n<p>A schema is not bureaucracy; it is validation the database does for free on your behalf. Refusing it doesn’t erase the bill; it just charges it to someone else.</p>\n<h2 id=\"the-crises-you-hit\">The crises you hit</h2>\n<p>Projects that start with the comfort of “schemaless” sooner or later hit these:</p>\n<ul>\n<li><strong>Data drift.</strong> Over time, ten different versions of a document live in the same collection. A record written in 2023 doesn’t have the same shape as one written in 2026, and no migration ever enforced it.</li>\n<li><strong>No referential integrity.</strong> An order pointing to a user that doesn’t exist isn’t blocked by the database. Orphan records pile up silently.</li>\n<li><strong>Migration becomes an application job.</strong> What a single <code>ALTER TABLE</code> does in the relational world becomes, here, a script that walks millions of documents one by one and has to be batched.</li>\n</ul>\n<p>These are invisible in a small project; they blow up at exactly the moment the project grows, the team changes, and no one can answer “why is that field sometimes missing?”</p>\n<h2 id=\"where-nosql-really-is-the-right-answer\">Where NoSQL really is the right answer</h2>\n<p>This is not an anti-NoSQL piece. NoSQL has real and justified uses:</p>\n<ul>\n<li>Workloads that exceed the write capacity of a single primary and genuinely need horizontal scale — the hardest breaking point in <a href=\"https://muhammetsafak.com/engineering/systems/data-intensive-systems-breaking-points/\">data-intensive systems</a>.</li>\n<li>Documents that are genuinely heterogeneous by nature.</li>\n<li>Specific access patterns — pure key-value, wide-column, graph.</li>\n</ul>\n<p>The trap isn’t NoSQL; it’s choosing NoSQL not for one of these real strengths but just because “I don’t want a schema.” Right tool, wrong reason.</p>\n<h2 id=\"if-you-want-flexibility-postgresql-already-gives-it\">If you want flexibility, PostgreSQL already gives it</h2>\n<p>If the need for “let some fields be flexible” is real, you don’t have to sacrifice all your integrity for it. PostgreSQL’s <code>jsonb</code> column gives you a flexible document field within the integrity of a relational table — as I touched on in <a href=\"https://muhammetsafak.com/engineering/essays/is-postgresql-enough-for-everything/\">is PostgreSQL enough for everything</a>. The fields that are fixed stay as schema, and the part that is genuinely variable lives in <code>jsonb</code>. The best of both, and in a single system.</p>\n<hr/>\n<p>A schema is not a burden; it is a shield. When you remove it from the database it doesn’t disappear — it just leaves the place where it protected you and moves to a place where it can’t.</p>\n<p>There is no such thing as “schemaless”; there is only the question of “who enforces the schema.”</p>",
      "content_text": "> **TL;DR:** There is no such thing as schemaless data, only the question of where the shape is defined and who enforces it. Choosing a document database for the comfort of not wanting a schema does not delete the schema; it moves it into every read, every write and the team's heads, where nothing enforces it. NoSQL earns its place on horizontal write scale or genuinely heterogeneous documents, not on schema avoidance.\n\nI once saw a project that had picked MongoDB on the logic of \"no schema, we'll move fast\" — two years later. Every read was defensive: `data?.user?.address?.city ?? null`. The reason was simple — no two documents had exactly the same shape. The schema hadn't disappeared; it had just left the database and scattered across every bit of code that reads a document.\n\n## \"Schemaless\" is a misnomer\n\nThere is no such thing as schemaless data. Data always has a shape: a user's email, the line items of an order, the date on an invoice. The question is not whether there is a shape; it is **where that shape is defined**.\n\nThere are two options. Either the schema lives in the database and is enforced by the database, or it lives in the application code and everyone is assumed to comply with it. Saying \"schemaless\" means choosing the second — not deleting the schema, but moving it somewhere it isn't enforced.\n\n## Where does the schema move?\n\nWhen the database stops enforcing the schema, that work doesn't vanish; it scatters to these places:\n\n- **To every read.** The code can no longer assume the incoming document has the expected fields; it checks every field defensively.\n- **To every write.** There is no guarantee you wrote the right shape; there is only hope.\n- **To scattered validation code.** The `NOT NULL`, type check, and foreign key that the database does in a single line all turn into hand-written checks.\n- **To the team's heads.** \"That field is sometimes a string, sometimes an array\" becomes undocumented tribal knowledge.\n\nA schema is not bureaucracy; it is validation the database does for free on your behalf. Refusing it doesn't erase the bill; it just charges it to someone else.\n\n## The crises you hit\n\nProjects that start with the comfort of \"schemaless\" sooner or later hit these:\n\n- **Data drift.** Over time, ten different versions of a document live in the same collection. A record written in 2023 doesn't have the same shape as one written in 2026, and no migration ever enforced it.\n- **No referential integrity.** An order pointing to a user that doesn't exist isn't blocked by the database. Orphan records pile up silently.\n- **Migration becomes an application job.** What a single `ALTER TABLE` does in the relational world becomes, here, a script that walks millions of documents one by one and has to be batched.\n\nThese are invisible in a small project; they blow up at exactly the moment the project grows, the team changes, and no one can answer \"why is that field sometimes missing?\"\n\n## Where NoSQL really is the right answer\n\nThis is not an anti-NoSQL piece. NoSQL has real and justified uses:\n\n- Workloads that exceed the write capacity of a single primary and genuinely need horizontal scale — the hardest breaking point in [data-intensive systems](/engineering/systems/data-intensive-systems-breaking-points/).\n- Documents that are genuinely heterogeneous by nature.\n- Specific access patterns — pure key-value, wide-column, graph.\n\nThe trap isn't NoSQL; it's choosing NoSQL not for one of these real strengths but just because \"I don't want a schema.\" Right tool, wrong reason.\n\n## If you want flexibility, PostgreSQL already gives it\n\nIf the need for \"let some fields be flexible\" is real, you don't have to sacrifice all your integrity for it. PostgreSQL's `jsonb` column gives you a flexible document field within the integrity of a relational table — as I touched on in [is PostgreSQL enough for everything](/engineering/essays/is-postgresql-enough-for-everything/). The fields that are fixed stay as schema, and the part that is genuinely variable lives in `jsonb`. The best of both, and in a single system.\n\n---\n\nA schema is not a burden; it is a shield. When you remove it from the database it doesn't disappear — it just leaves the place where it protected you and moves to a place where it can't.\n\nThere is no such thing as \"schemaless\"; there is only the question of \"who enforces the schema.\"\n\n## Sources\n\n- [Designing Data-Intensive Applications, Chapter 2: schema-on-read vs. schema-on-write](https://dataintensive.net/) — Martin Kleppmann, O'Reilly Media, 2017\n- [MongoDB Manual: Schema Validation](https://www.mongodb.com/docs/manual/core/schema-validation/) — MongoDB\n- [JSON Types: jsonb](https://www.postgresql.org/docs/current/datatype-json.html) — PostgreSQL\n\n## Frequently asked\n\n### Is any data really schemaless?\n\nNo. Data always has a shape; the only question is where that shape is defined. Either the database holds the schema and enforces it, or the application code holds it and everyone is assumed to comply. Schemaless means choosing the second.\n\n### When is NoSQL genuinely the right choice?\n\nWhen the workload exceeds the write capacity of a single primary and needs real horizontal scale, when documents are heterogeneous by nature, or when the access pattern is specific: pure key-value, wide-column, graph. Not wanting a schema is not one of those reasons.",
      "date_published": "2026-08-08T00:00:00.000Z",
      "date_modified": "2026-09-06T00:00:00.000Z",
      "tags": [
        "nosql",
        "database",
        "architecture",
        "opinion"
      ],
      "authors": [
        {
          "name": "Muhammet Şafak",
          "url": "https://muhammetsafak.com"
        }
      ]
    }
  ]
}