<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umar Tahir on Medium]]></title>
        <description><![CDATA[Stories by Umar Tahir on Medium]]></description>
        <link>https://medium.com/@umartahir93?source=rss-228101f85f71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gzNookmh8fgjtb6NCdq5Lw.jpeg</url>
            <title>Stories by Umar Tahir on Medium</title>
            <link>https://medium.com/@umartahir93?source=rss-228101f85f71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:42:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umartahir93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scale One Order of Magnitude at a Time]]></title>
            <link>https://umartahir93.medium.com/scale-one-order-of-magnitude-at-a-time-c9fc845e4144?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9fc845e4144</guid>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 09:21:49 GMT</pubDate>
            <atom:updated>2026-11-13T09:21:49.274Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What I learned from rethinking scalability, and from migrating our data store at work.</em></p><p>I’ve been reading <em>Designing Data-Intensive Applications</em> by Martin Kleppmann. One idea in the chapter on scalability stopped me, because it described something I’d lived through without having a name for it:</p><blockquote><em>An architecture that’s right for one level of load is unlikely to cope with 10× that load.</em></blockquote><p>It sounds simple. But it changes how you should think about designing systems, and it changes how much future-proofing is worth doing. Here’s how I understand it.</p><h3>1. Every design rests on assumptions about load</h3><p>When you design a system, you’re making assumptions, whether you write them down or not:</p><ul><li>“One database can handle all our writes.”</li><li>“We can compute this report live when someone asks for it.”</li><li>“A nightly batch job is fast enough.”</li><li>“Every request can hit the same service.”</li></ul><p><strong>At the load you designed for, these assumptions hold</strong>. That’s why the design works. When load grows by an order of magnitude, roughly 10×, some of them stop being true. The database that was comfortably handling writes is now the bottleneck. The live query that took 200 ms now takes 20 seconds. The nightly job doesn’t finish before morning.</p><p><strong>The system doesn’t fail because it was badly designed. It fails because the assumptions it was designed around have expired.</strong></p><h3>2. Expect to rethink the architecture at each 10× jump</h3><p>If your service is growing fast, this happens again and again. Roughly:</p><ul><li><strong>1k → 10k users:</strong> you add caching, read replicas, maybe a queue.</li><li><strong>10k → 100k users:</strong> the single-leader database or the monolith may become the wall. Now you’re talking about partitioning, separate services, or a different storage engine.</li><li><strong>100k → 1M users:</strong> new bottlenecks appear in places that were never a concern before.</li></ul><p>The key point is that these aren’t tweaks. Adding another server of the same kind usually isn’t enough. You have to change the <em>shape</em> of the system. Often it isn’t the whole architecture, just the part that has become the bottleneck, but it is a real redesign.</p><p>So scalability isn’t something you design in once. You keep earning it as you grow.</p><h3>3. Don’t plan more than one order of magnitude ahead</h3><p>This is the practical advice, and it’s the part I find most useful. The temptation is to design for “massive scale” from day one, with sharding, event streaming and microservices, just in case. The book’s argument is that this is usually not worth it, because you don’t know what your system will look like at 100× today:</p><ul><li>Will it be read-heavy or write-heavy?</li><li>Will you have many small users, or a few large ones requesting huge amounts of data?</li><li>Which features will people actually use?</li><li>Where will the real bottlenecks be?</li></ul><p>If you build for imagined future scale, you’ll probably:</p><ol><li><strong>Optimize for the wrong bottleneck</strong>, because your guesses about future usage are likely wrong.</li><li><strong>Pay for complexity today.</strong> Distributed systems are harder to build, debug and change, and that slows down the team now, when speed matters most.</li><li><strong>Redesign anyway</strong> once real requirements show up and differ from what you predicted.</li></ol><p>The sweet spot is to <strong>design for your current load, leave headroom for about 10×, and plan to redesign as you approach that ceiling.</strong></p><h3>A real example: our migration to ClickHouse</h3><p>This idea clicked for me because of a project I led at work. We moved measurement data from an internal data lake to ClickHouse.</p><p>The data lake setup was designed for the load and use cases we had at the time, with some headroom. It worked. As the platform grew, both the volume of data and the ways people needed to query it changed. The original design’s assumptions stopped fitting, and adding more of the same wasn’t going to fix it. We needed a different storage architecture.</p><p>The important part is <em>when</em> we made that move. We didn’t migrate on day one based on guesses. <em>We migrated once we had enough real information: we could see the actual query patterns, the real data volumes and where the system was struggling. That let us choose a design that fit real needs instead of imagined ones.</em></p><p>If we had tried to build the “final” architecture at the start, we’d have been optimizing for query patterns that didn’t exist yet, and we’d probably have chosen wrong.</p><h3>The takeaway</h3><p>If I had to fit the whole idea into one line, it would be:</p><p><strong>Design for today with room for 10×, expect to redesign at each 10× jump, and don’t over-build beyond that, because you can’t predict what the future load will look like.</strong></p><p>Scaling isn’t about predicting the future perfectly. It’s about building something that works now, noticing when its assumptions start to break, and being ready to redesign when you have real data to guide you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fc845e4144" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency, by doing it Guide]]></title>
            <link>https://umartahir93.medium.com/idempotency-by-doing-it-guide-106325f057ff?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/106325f057ff</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 16:05:29 GMT</pubDate>
            <atom:updated>2026-10-24T16:05:29.403Z</atom:updated>
            <content:encoded><![CDATA[<p>An operation is idempotent if doing it multiple times has the same effect as doing it once. It matters because, in a distributed system,<strong> “twice” is going to happen.</strong></p><p>For example: you send “charge €10” to a server. No reply comes. Three different things could have happened:</p><ol><li>The request was lost on the way. Nothing was charged.</li><li>The server crashed halfway through. Maybe charged.</li><li>The server charged the money, but the reply got lost. Charged.</li></ol><p>From the client’s side all three look the same: <strong><em>a timeout</em></strong>. Point is that a <strong><em>timeout means unknown, not failed</em></strong>. So the client has two options:</p><ul><li>Don’t retry: some payments are lost (case 1).</li><li>Retry: some payments are charged twice (case 3).</li></ul><p>Neither is acceptable for some use cases e.g. payment. <strong>So you need a third option: make retrying safe.</strong> “<strong>That’s idempotency</strong>.” It’s not a nice extra; it’s the price of retrying, and in a distributed system you have to retry.</p><blockquote>🧠 The chain to remember:<br>timeout = unknown → I must retry → a retry must be safe → make the operation idempotent.</blockquote><h3><strong>Now question is what can be Idempotent?</strong></h3><p>Almost every layer (e.g. HTTP, database transaction, calls to external service etc) can be made idempotent, and in a real system (i.e. where it matters) every layer has to be. Duplicates come from different places in each layer,<strong> but the fix is always the same idea</strong>:</p><blockquote>Give the <strong>operation a stable identity</strong>, and <strong>record “done” for that identity</strong> in the <strong>same atomic step as the effect.</strong></blockquote><p>If “record done” and “do the effect” happen as two separate steps, a crash between them gives you either a duplicate or a lost operation.</p><p>For any component, ask three questions:<br>1. Where can a duplicate come from? (client retry, redelivery, a job re-run, a zombie worker)<br>2. What is the operation’s stable identity? (idempotency key, event ID, job + date, offset)<br>3. Where is “done” recorded, and is it atomic with the effect?</p><h3>Layer by layer</h3><h4>1. HTTP API</h4><ul><li><strong>Where duplicates come from:</strong> the client retries after a timeout.</li><li><strong>Natural</strong>: GET, PUT (replace the whole resource) and DELETE are idempotent by design. The effect is the same, but the response can differ. A second DELETE may return 404. <strong><em>Idempotency is about Server state, not Identical Replies</em></strong>.</li><li><strong>Made idempotent (</strong>POST + an Idempotency-Key header): The POST + Idempotency-Key header option is the industry standard to make state changing POST requests idempotent.</li><li>In HTTP terms, PATCH is not guaranteed idempotent (RFC 5789). <strong>It depends on the bod</strong>y: A JSON Merge Patch with absolute values ({“amount”: 110}) is idempotent. A JSON Patch operation like add to an array isn’t.</li><li><strong>Where “done” is recorded:</strong> a row in an idempotency_keys table holding the key, a hash of the request body, the status (IN_PROGRESS or COMPLETED) and the stored response. A unique constraint on the key means only one request can claim it, even when two retries arrive at the same moment. The row is written in the same database transaction as the change it protects (e.g. the new payment), so both are saved or neither is. A retry finds the key and gets the stored response instead of a second charge. In case of external calls, an HTTP call to a provider can’t be rolled back, so the work is split into steps. Commit the key as IN_PROGRESS, call the provider with our payment ID as their idempotency key, then save the result in a second transaction. After a crash, a retry resumes the unfinished request and the provider recognises the same ID, so nothing is charged twice.</li><li>This key, doesnt have to stay in the database eternally. You can clean up according to your usecases.</li></ul><h4>2. Database transactions</h4><ul><li><strong>Where duplicates come from:</strong> the transaction committed, but the acknowledgement was lost, so the app retries the whole transaction. Retrying an aborted-looking transaction that actually committed runs it twice unless you have your own deduplication. A transaction gives you atomicity (all or nothing), not idempotency (once only). They’re different guarantees.</li><li>Made idempotent: Dedupe row in the same transaction: insert the key with a unique constraint, then do the work. If the key exists, the whole transaction becomes a no-op OR Conditional writes: UPDATE … WHERE status = ‘PENDING’, or WHERE version = 7 (optimistic locking). Upsert with absolute values: INSERT … ON CONFLICT (id) DO UPDATE <strong>SET amount = 1000 is idempotent;</strong> <strong>SET amount = amount + 10 isn’t</strong>.</li></ul><blockquote>🧠 To remember: ACID = each run is correct. Idempotency = only one run counts. Different guarantees; you need both.</blockquote><h4>3. Calls to external services (providers, banks)</h4><ul><li><strong>Where duplicates come from:</strong> your retry to a partner after a timeout.</li><li><strong>Made idempoten</strong>t:<br> — Pass your own operation ID downstream as the partner’s idempotency key.<br> — If the partner has no keys: you can’t make the call itself idempotent. Your options:<br> — Check before retrying: ask “what’s the status of order 42?” before sending again.<br> — Don’t retry automatically, and leave it to reconciliation (compare your records with theirs later).</li><li><strong>Hard truth:</strong> for an external side effect with no dedupe support, you must choose:<br> — at-most-once: never retry, accept occasional loss<br> — at-least-once: retry, accept occasional duplicates</li></ul><p>This choice matters for emails and SMS too: a duplicate email is usually acceptable, a duplicate charge isn’t.</p><h4>4. Message queues and events (SQS, Kafka, webhooks)</h4><p>Duplicates come from two sides:</p><ul><li><strong>Producer side:</strong> the producer retries a send, or the outbox relay crashes after publishing but before marking the row as sent, so it publishes again.<br> — Fix: every event <strong>carries a stable event_id</strong>, created once when the event is created, not when it’s sent.<br> — Kafka’s idempotent producer (producer ID + sequence number, deduplicated by the broker) handles the retries within the client.</li><li><strong>Consumer side</strong>: the consumer processes a message, crashes before the ack or offset commit, and the message is delivered again (at-least-once).<br> — Fix A: a processed_events(event_id) table in the same transaction as the effect.<br> — Fix B: save the consumed offset in the same DB transaction as the result. On restart, continue from the saved offset.<br> — Fix C: <strong>make the effect naturally idempotent </strong>(conditional state change).</li><li>Gotcha: duplicates ≠ out of order. Dedupe doesn’t save you if “refunded” arrives before “captured”.<br> — Fix: a state machine (only allowed transitions), or apply an event only when<strong> event.version &gt; current.version</strong>.<br> — Order is only guaranteed per partition key, so partition by payment ID.</li></ul><h4>5. Stream processing (Flink, Kafka Streams)</h4><ul><li><strong>Where duplicates come from: </strong>after a crash, the processor restores a checkpoint and replays input from there. Everything after the checkpoint is processed again.</li><li><strong>Made idempotent:</strong><br> — Checkpoint + idempotent sink: replays overwrite the same keys (upsert by key) instead of appending.<br> — Atomic commit: the output and the input offset commit together (Kafka transactions: read → process → write as one transaction).</li><li><strong>Conditions for replay to be safe:<br></strong> — the processing is deterministic (no now() or random values inside)<br> — the replay reads the same input in the same order<br> — no zombie instance is still writing. A fencing token or epoch rejects writes from the old instance.</li></ul><h4><strong>6. Batch processing</strong></h4><ul><li><strong>Where duplicates come from:</strong> a job fails halfway and is re-run, or someone runs it twice.</li><li><strong>Not idempotent:</strong> “append yesterday’s rows to the table”. Run it twice and you have double the rows.</li><li><strong>Made idempotent:</strong> treat a job as a pure function: immutable input → output.<br> — Overwrite, don’t append: write to a new location, then swap atomically (replace the date=2026–10–23 partition, or swap tables).<br> — MERGE / upsert on a natural key instead of a plain insert.<br> — Big benefit: a re-run is always safe, so “fix the bug and run it again” becomes a normal recovery tool.</li></ul><h4>7. Scheduled jobs (cron)</h4><ul><li><strong>Where duplicates come from: </strong>two instances both fire, or a retry after a timeout.</li><li><strong>Fix</strong>: a `unique job_runs(job_name, run_date)` row inserted first, plus a lease/lock with a fencing token. The second run finds the row and stops.</li></ul><pre>Merchant ──&gt; POST + Idempotency-Key──▶ API<br>                                       │  ① dedupe: key row + unique constraint<br>                                       ▼<br>                               Payment DB (tx: payment PENDING + key + outbox event)<br>                                       │  ② same transaction = atomic &quot;done&quot;<br>                                       ▼<br>                     Outbox relay ──event_id──▶ Queue<br>                                       │  ③ duplicates possible → stable event_id<br>                                       ▼<br>                   Connector ──our payment_id as their key──▶ Provider<br>                                       │  ④ end-to-end key; no support → status check<br>                                       ▼<br>          Provider webhook (twice / late) ──▶ Status consumer<br>                                       │  ⑤ processed_events + conditional state change<br>                                       ▼<br>                 Merchant webhook (retries ~68 h) ──event_id──▶ Merchant<br>                                       │  ⑥ the merchant must dedupe by event_id too<br>                                       ▼<br>                 Nightly reconciliation (batch, overwrite per day)<br>                                          ⑦ re-runnable; catches anything ①–⑥ missed</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106325f057ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Views: A Complete Field Guide]]></title>
            <link>https://umartahir93.medium.com/postgresql-views-a-complete-field-guide-5d923c12e2fa?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d923c12e2fa</guid>
            <category><![CDATA[rename-table]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Mon, 11 May 2026 15:39:36 GMT</pubDate>
            <atom:updated>2026-05-11T15:39:36.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fzxjCtoBcGOSF64" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Everything you need to confidently use, abuse, and avoid the traps of views in production PostgreSQL systems.</em></blockquote><h3>What Is a View, Really?</h3><p>A view is a <strong>named query stored in the database catalog</strong>. What happens when you query it depends entirely on the type of view.</p><p>For a regular view, PostgreSQL intercepts your query before planning and rewrites it — substituting the view’s definition inline. By the time the query reaches the planner, the view is gone, replaced by its underlying SQL. For simple regular views (single table, no aggregation), this rewrite is fully inlined: the planner works directly against the base table as if the view never existed.</p><p>For complex regular views (joins, aggregates, UNION), the rewrite happens but produces a subquery boundary that the planner cannot collapse. The view becomes an optimization fence.</p><p>For materialized views, there is no rewrite at all. PostgreSQL treats them as physical tables with their own storage, indexes, and statistics. Querying a materialized view is identical to querying a real table.</p><pre>CREATE VIEW active_orders AS<br>  SELECT id, customer_id, total FROM orders WHERE status = &#39;active&#39;;<br><br>-- Your query:<br>SELECT * FROM active_orders WHERE customer_id = 42;<br><br>-- What PostgreSQL actually plans (for this simple view):<br>SELECT id, customer_id, total FROM orders<br>WHERE status = &#39;active&#39; AND customer_id = 42;</pre><h3>The Six Types of Views</h3><h4>1. Regular View (Simple)</h4><p>The default. A stored SQL query with no data on disk. Every query re-executes the underlying SQL — always fresh, always as fast or slow as the base tables.</p><pre>CREATE VIEW recent_signups AS<br>  SELECT id, email, created_at FROM users<br>  WHERE created_at &gt; NOW() - INTERVAL &#39;30 days&#39;;</pre><p>When the view is simple (single table, no aggregation, no DISTINCT — full criteria below), PostgreSQL fully inlines it. The planner sees the base table directly, uses its indexes, and its statistics. Zero overhead compared to querying the table directly.</p><p>When the view is complex, inlining cannot happen. See the optimization fence section below.</p><h4>2. Materialized View</h4><p>Stores the query result on disk like a physical table. Must be explicitly refreshed. Has its own statistics and supports all index types.</p><pre>CREATE MATERIALIZED VIEW monthly_revenue AS<br>  SELECT DATE_TRUNC(&#39;month&#39;, created_at) AS month,<br>         SUM(amount) AS revenue<br>  FROM orders GROUP BY 1;<br><br>-- Refresh:<br>REFRESH MATERIALIZED VIEW monthly_revenue;              -- blocks reads during refresh<br>REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue; -- non-blocking, needs unique index</pre><p>REFRESH CONCURRENTLY requires a UNIQUE index and is slower than a regular refresh, but does not block reads. Use it in production. A regular REFRESH takes an exclusive lock for the entire duration.</p><p><strong>When to use:</strong> Reports, dashboards, and expensive aggregations you can tolerate being slightly stale. Nightly batch jobs that produce summary data.</p><h4>3. Updatable View</h4><p>Not a different CREATE syntax — it is a property a regular view either has or does not have. When a view qualifies, PostgreSQL automatically allows INSERT, UPDATE, and DELETE through it, rewriting them to target the base table.</p><p>A view is automatically updatable when ALL of these hold:</p><ul><li>Built on a single base table (no joins)</li><li>No DISTINCT, GROUP BY, HAVING</li><li>No LIMIT, OFFSET</li><li>No window functions or aggregate functions</li><li>No UNION, INTERSECT, EXCEPT</li><li>All columns in SELECT are simple column references (no expressions, no computed columns)</li></ul><pre>-- Qualifies as automatically updatable:<br>CREATE VIEW active_users AS<br>  SELECT id, email, name FROM users WHERE deactivated_at IS NULL;<br><br>INSERT INTO active_users (id, email, name) VALUES (1, &#39;a@b.com&#39;, &#39;Alice&#39;);  -- works<br>UPDATE active_users SET name = &#39;Alicia&#39; WHERE id = 1;                       -- works<br>DELETE FROM active_users WHERE id = 1;                                      -- works</pre><p>RETURNING works through updatable views (since PostgreSQL 9.3):</p><pre>UPDATE active_users SET name = &#39;Alicia&#39; WHERE id = 1 RETURNING id, name;   -- works</pre><p><strong>ON CONFLICT does NOT work through views</strong> — this is a hard PostgreSQL limitation. The target of INSERT … ON CONFLICT DO UPDATE must be a physical table</p><pre>INSERT INTO active_users (id, email) VALUES (1, &#39;a@b.com&#39;)<br>ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;<br>-- ERROR: ON CONFLICT DO UPDATE is not supported for views</pre><p>This limitation has real consequences in migration scenarios — covered in detail later.</p><h4>4. WITH CHECK OPTION</h4><p>An addition to an updatable view that prevents writes from producing rows invisible to the view.</p><pre>CREATE VIEW active_users AS<br>  SELECT * FROM users WHERE deactivated_at IS NULL<br>  WITH CHECK OPTION;<br><br>-- Without CHECK OPTION, this succeeds but the row becomes invisible to the view:<br>UPDATE active_users SET deactivated_at = NOW() WHERE id = 1;<br>-- With CHECK OPTION:<br>-- ERROR: new row violates check option for view &quot;active_users&quot;</pre><p>Use this when the view encodes a business constraint that writes must respect — it turns the view into a guarded write path, not just a read filter.</p><h4>5. Recursive View</h4><p>Syntactic sugar over a recursive CTE. Used for hierarchical, tree-structured data.</p><pre>CREATE RECURSIVE VIEW org_chart(id, name, manager_id, depth) AS<br>  -- Base case: top-level employees<br>  SELECT id, name, NULL::int, 0<br>  FROM employees WHERE manager_id IS NULL<br>  UNION ALL<br>  -- Recursive case: direct reports<br>  SELECT e.id, e.name, e.manager_id, oc.depth + 1<br>  FROM employees e JOIN org_chart oc ON e.manager_id = oc.id;</pre><h4>6. security_barrier View</h4><p>A regular view with a flag that intentionally blocks inlining to prevent data leakage via user-controlled functions.</p><pre>CREATE VIEW my_data WITH (security_barrier) AS<br>  SELECT * FROM sensitive_table WHERE owner_id = current_user_id();</pre><p>Without security_barrier, a sophisticated attacker can pass a leaky function in a WHERE clause that executes before the view’s filter — leaking row existence through timing or error messages. The barrier forces the view’s WHERE to always evaluate first.</p><p>Performance cost: security_barrier is an optimization fence. The planner cannot push predicates into the view. This can significantly hurt performance. Only use it when the security concern is real.</p><h3>Performance: The Full Picture</h3><h4>Simple Regular Views — Truly Zero Overhead</h4><p>For views that meet the automatically-updatable criteria (single table, no aggregation, no DISTINCT, etc.), PostgreSQL completely inlines the view at the rewrite stage. The planner never sees the view name — it plans directly against the base table.</p><pre>EXPLAIN SELECT * FROM active_users WHERE id = 42;<br><br>-- Output shows:<br>Index Scan using users_pkey on users   ← &quot;users&quot;, not &quot;active_users&quot;<br>  Index Cond: (id = 42)<br>  Filter: (deactivated_at IS NULL)</pre><p>The view is gone. Indexes on the base table are used. Statistics on the base table drive the plan. There is no measurable performance difference between querying the view and querying the table directly.</p><h4>Complex Regular Views — The Optimization Fence</h4><p>When a view contains aggregations, GROUP BY, UNION, window functions, or joins, PostgreSQL cannot inline it. It must plan the view’s inner query independently, then plan the outer query independently. These two plans cannot be merged — the view becomes a wall.</p><pre>CREATE VIEW customer_order_counts AS<br>  SELECT customer_id, COUNT(*) AS total<br>  FROM orders GROUP BY customer_id;<br><br>-- PostgreSQL CANNOT push this filter into the view:<br>SELECT * FROM customer_order_counts WHERE customer_id = 42;<br><br>-- It computes ALL customer_order_counts first, then filters.<br>-- On a large orders table, this processes millions of rows to return one.</pre><p>Verify with EXPLAIN:</p><ul><li>Inlining happened → Seq Scan on orders or Index Scan on orders</li><li>Optimization fence → Subquery Scan on customer_order_counts</li></ul><p><strong>The fix:</strong> use CTEs or subqueries in application code rather than wrapping complex logic in views and then filtering outside them</p><h4>Materialized Views — Own Their Own Performance</h4><p>Materialized views are not inlined and not rewritten. They have their own statistics (collected by autovacuum/ANALYZE) and support all index types:</p><pre>CREATE MATERIALIZED VIEW mv AS SELECT ...;<br>CREATE UNIQUE INDEX ON mv (id);           -- required for CONCURRENTLY refresh<br>CREATE INDEX ON mv (customer_id);<br>CREATE INDEX ON mv USING gin (tags);      -- full-text, JSONB, arrays</pre><p>Query performance is equivalent to a regular table. The trade-off is staleness and refresh cost.</p><h3>Views and Prepared Statements in Production</h3><p>This is where views get critical in live systems.</p><h4>How Prepared Statements Work</h4><p>When your application prepares a SQL statement (explicitly via PREPARE, or implicitly through an ORM or database driver), PostgreSQL:</p><ol><li>Parses the SQL</li><li>Plans the query against the current schema</li><li>Stores the plan per connection in memory</li></ol><p>The plan is not stored globally — it lives for the lifetime of that database connection. A connection pool with 20 connections means 20 independent cached plans.</p><h4>DDL Invalidates Plans — Transparently</h4><p>When you run DDL (ALTER TABLE, CREATE VIEW, DROP VIEW, etc.), PostgreSQL automatically invalidates all cached plans that reference the affected relation. The next time your application executes one of those prepared statements, PostgreSQL detects the stale plan and transparently replans before executing. Your application sees no error. No reconnect is needed. This happens silently.</p><pre>t=0  App starts<br>     Prepared statement cached: SELECT * FROM orders WHERE id = $1<br>     Plan: Index Scan on orders<br><br>t=1  Migration runs:<br>     ALTER TABLE orders RENAME TO order_records;<br>     CREATE VIEW orders AS SELECT * FROM order_records;<br><br>t=2  All plans referencing &quot;orders&quot; are invalidated<br><br>t=3  App executes prepared statement<br>     PostgreSQL: plan stale → replan against &quot;orders&quot; (now a view)<br>     View inlined → new plan: Index Scan on order_records<br>     App receives results normally — no error, no awareness of change</pre><h4>The Real Traffic Risk: The Lock</h4><p>ALTER TABLE … RENAME takes an ACCESS EXCLUSIVE lock. For the duration of the rename — typically under 1 millisecond — all concurrent reads and writes are queued, not rejected. They resume the instant the lock is released. Goroutines or threads waiting on the table receive their results with a slight delay. They do not receive errors.</p><p>The only scenario that produces errors is a query timeout shorter than the lock wait — something like &lt;5ms, which is atypically aggressive.</p><p>Mitigation: Run the rename during off-peak hours. The lock window is milliseconds.</p><h3>The Rename-With-Compatibility-View Pattern</h3><p>The most practical production application of everything we learned above: <strong>renaming a heavily-trafficked table with zero downtime</strong>.</p><h4>The Problem</h4><p>You need to rename legacy_name to new_name. Your application has SQL references to legacy_name spread across the codebase. You cannot deploy the code change and the database migration atomically — deployments are rolling or canary</p><pre>BEGIN;<br>ALTER TABLE legacy_name RENAME TO new_name;<br>CREATE VIEW legacy_name AS SELECT * FROM new_name;<br>COMMIT;</pre><p>Inside a single atomic transaction: rename the table, then create a view with the old name pointing to the new table. Old code continues hitting the view transparently. New code can be deployed at leisure targeting new_name directly.</p><h4>The Deploy Sequence</h4><pre>Step 1: Run migration (rename + create view)<br>          Old code → legacy_name → view → new_name  ✓<br>          New code → not yet deployed<br><br>Step 2: Deploy new code (rolling or canary — both fine)<br>          Old code → legacy_name → view → new_name  ✓<br>          New code → new_name → table directly       ✓<br>          Both work simultaneously<br><br>Step 3: Confirm all old instances drained<br>          ↓<br>Step 4: Run cleanup migration: DROP VIEW legacy_name<br>          New code → new_name → table directly       ✓</pre><p><strong>Critical</strong>: Drop the view only after confirming that zero old-code instances are still running. If you drop it prematurely, old instances will get ERROR: relation “legacy_name” does not exist on their next replan attempt</p><h3>The ON CONFLICT Blocker</h3><p>If your old code uses INSERT … ON CONFLICT against the table being renamed, the compatibility view will not work for those write paths. The view will cause:</p><p>ERROR: ON CONFLICT DO UPDATE is not supported for views</p><p>Your options:</p><p><strong>Option A — INSTEAD OF trigger:</strong> Write a trigger that handles the upsert manually. The view stays, writes go through the trigger, zero downtime is preserved. More code, but fully compatible with rolling/canary deployments.</p><p><strong>Option B— Maintenance window:</strong> If the table with ON CONFLICT is an internal detail with no external consumers, a brief planned window is often the least risky option.</p><p><strong>Option C — Temporarily Add App code to reflect the logic:</strong> You can move the on Conflict logic to application logic temporarily, after the migration, these changes can be undone to use the ON Conflict clause.</p><h3>Quick Reference</h3><ul><li><strong>Does a simple regular view add query overhead? </strong>No — fully inlined at rewrite time</li><li><strong>Does a complex regular view add overhead? </strong>Yes — becomes an optimization fence (subquery scan)</li><li><strong>Does a materialized view get inlined? </strong>No — queried as a physical table</li><li><strong>Do base-table indexes work through a simple view? </strong>Yes — fully transparent</li><li><strong>Does RETURNING work through updatable views? </strong>Yes (PG 9.3+)</li><li><strong>Does ON CONFLICT work through views? </strong>No — hard limitation</li><li><strong>Does DDL break prepared statements? </strong>No — transparent replan on next <strong>execution.</strong></li><li><strong>What lock does ALTER TABLE RENAME take? </strong>ACCESS EXCLUSIVE</li><li><strong>How to verify a view is being inlined? </strong>EXPLAIN — look for scan on base table, not Subquery Scan on <strong>view.</strong></li><li><strong>When is a view automatically updatable? </strong>Single table, no aggregation, no DISTINCT, no UNION, no expressions in <strong>SELECT.</strong></li><li><strong>Can materialized views have indexes? </strong>Yes — all index <strong>types.</strong></li><li><strong>Does REFRESH block reads? </strong>Regular: yes. CONCURRENTLY: no (needs unique index)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d923c12e2fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Architecture Diagram is Lying to You | A Practical Guide to Context Mapping]]></title>
            <link>https://blog.stackademic.com/your-architecture-diagram-is-lying-to-you-a-practical-guide-to-context-mapping-3378e0b07548?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/3378e0b07548</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 14:37:50 GMT</pubDate>
            <atom:updated>2026-05-04T07:33:58.020Z</atom:updated>
            <content:encoded><![CDATA[<p>If you walk into any enterprise engineering department and ask to see their architecture, they will proudly hand you a diagram. It will be a beautiful, sterile picture of boxes (microservices) connected by neat little arrows (REST APIs or Kafka streams).</p><p>I look at those diagrams, and I see a lie.</p><p>Those diagrams tell me how the JSON flows. They tell me absolutely nothing about why your teams are burning out, why your sprint is delayed by three weeks, why your developers can’t own their domains, or why they hate coming to work on Fridays.</p><p>Software architecture is not just technical. It is <strong>sociotechnical</strong>. Code does not exist in a vacuum; it is written by human beings who are constrained by company politics, budgets, and communication bottlenecks.</p><h3>What is a Context Map, and Why is it Essential?</h3><p>A Context Map is a diagnostic tool from Strategic DDD. On the page, it looks deceptively simple: Bounded contexts connected by labeled lines describing the nature of their relationship. But those labels are where the honesty lives.</p><p>A Context Map forces you to name the relationship not just the connection. At its core it reveals three things: who holds power, how much coordination teams require, and how teams technically protect themselves from each other.</p><p><strong>Who holds power:</strong> Every team relationship sits somewhere on a spectrum.</p><ul><li>At one end, “Separate ways” — two teams with no integration, no dependency, no problem.</li><li>At the other end, “Conformist” — you take what the upstream gives you, on their timeline, with no say.</li><li>In between sits <strong>Customer-Supplier</strong>, where the downstream team has real negotiating power. And <strong>Shared Kernel</strong>, where two teams co-own a shared model and neither can move without the other’s agreement.</li></ul><p>Where your relationships fall on this spectrum tells you immediately where your bottlenecks live.</p><p><strong>How much coordination teams require:</strong> Some teams are deeply entangled — every decision requires a joint meeting, every release needs sign-off from both sides. Others are loosely coupled, moving independently with minimal friction. A Context Map makes this visible by forcing you to label it. That label alone will tell you whether your coordination overhead is<br> a deliberate architectural choice or an accident nobody has bothered to fix yet.</p><p><strong>How teams protect themselves from each other:</strong> Not every team can trust that their neighbors will be careful. Sometimes an upstream team has a messy model, a legacy system, or simply no incentive to make your life easy. A Context Map names how your team has chosen to handle that — whether you’ve built explicit barriers to stop bad models from leaking into your codebase, or whether you’ve left yourself exposed. This is where architecture stops being about design and starts being about self-defense.</p><h4>Why does this matter? The Cost of Change.</h4><p>The true nature of any architectural relationship is ultimately revealed by one question: <strong>whose change causes whose pain?</strong></p><p>If the legacy ERP team changes their database schema on a Friday at 4 PM without telling you, and your team cancels their weekend plans to rewrite the integration, they hold the power. Your architecture diagram shows a neat arrow between two boxes. Your Context Map would label that arrow Conformist, and suddenly, the political reality is visible to everyone<br> in the room.</p><p>That is not a technical problem. No amount of cleaner code, better abstraction, or faster CI pipelines will fix it. It is a power dynamic baked into your organizational structure, <strong>and the only way to address it is to first be honest that it exists</strong>.</p><h3>Why You Need Different Perspectives</h3><p>The biggest mistake architects make is trying to draw one diagram that solves every problem.</p><p>Think of a Context Map like Google Maps. Same city, different lens. You don’t use satellite view to check traffic, and you don’t use traffic view to find a hiking trail. Toggle the wrong lens, and you’ll prescribe the wrong solution.</p><p>A Context Map works the same way. There are many lenses you can apply, each tackling a different class of problem. In this article, we focus on three — the ones that cause the most damage in most organizations.</p><p><strong>The Political Lens:</strong> Who holds power and who doesn’t. This is the view you pull up when your sprint is blocked, your budget is overrun, and nobody can tell you why. You’re not looking for clean code here — you’re looking for the upstream team that doesn’t know your name and doesn’t care about your deadline.</p><p><strong>The Communication Lens:</strong> Who needs to talk to whom, and how often. This is the view you pull up when your developers are in six meetings a day and shipping nothing. Which teams need a shared channel? Which teams need to be in your planning meetings? Which teams can you safely ignore?</p><p><strong>The Technical Lens:</strong> Where your models are leaking and where they’re protected. This is the view you pull up when a schema change in a system you don’t own breaks your production build at 2 AM. Are you consuming their JSON directly, or have you built a wall between their chaos and your clean domain?</p><h3>The Patterns: Your Architectural Toolbelt</h3><p>Once you have chosen your lens, DDD gives you a specific vocabulary to describe what you are actually looking at. You don’t use these patterns to design a utopian future. You use them to diagnose your reality as it exists today.</p><h4>When the problem is power:</h4><p><strong>Conformist:</strong> You have no leverage. The upstream team does not know your name and does not care about your roadmap. You consume whatever they publish, in whatever shape they publish it, on whatever timeline suits them. You simply adapt.</p><p><strong>Customer-Supplier: </strong>Power is negotiated. You have a seat at the table. If you need a new API field, you raise it, they prioritize it, and they build it. It is not equal — they are still upstream — but the relationship is deliberate and the communication flows both ways.</p><p><strong>Separate Ways:</strong> You take your power back by walking away. The political friction of integrating with a particular team is so high that you are better off solving the problem yourself.<br> It is not a failure. Sometimes it is the most rational architectural decision you can make.</p><h4>When the problem is coordination:</h4><p><strong>Partnership:</strong> Maximum coordination, shared accountability. Both teams plan together, both teams succeed or fail together. This only works when both sides have equal skin in the game — the moment that balance tips, a Partnership quietly becomes a Customer-Supplier.</p><p><strong>Shared Kernel:</strong> Two teams share a common piece of code or a data model. Neither can change it without the other’s agreement. It sounds efficient until you realize every change requires a conversation, and every conversation takes a calendar invite.</p><h4><strong>When the problem is code:</strong></h4><p><strong>Anticorruption Layer (ACL): </strong>You are integrating with a system that is a mess — legacy models, inconsistent data, decades of technical debt. Rather than letting their chaos leak into your codebase, you build a translation layer. It costs CPU cycles and engineering time, but it keeps your domain clean.</p><p><strong>Open Host Service (OHS):</strong> The upstream team does the right thing. They publish a stable, well-defined API and maintain it deliberately so that downstream teams can integrate without pain. Consumers read the docs and build. No meetings required.</p><p><strong>Published Language (PL):</strong> Both teams agree to communicate using a shared, standardized format — an industry standard schema, a common event format, a well-known protocol. Nobody owns it. Nobody can break it unilaterally.</p><p>If you want to go deeper on each pattern, what they look like in practice, when to use them, and when to avoid them, I cover them in detail <a href="https://medium.com/p/88eb03baeebe/edit">here</a>.</p><h3>The Reality of Stacking</h3><p>In the real world, you do not pick one pattern and move on. You stack them.</p><p>A single integration line can carry multiple labels at once — and that is not a design flaw, that is just reality. For example:</p><p>Look at the line between your Inventory service and a third-party Billing API. It is probably all of these simultaneously:</p><ul><li>They built a clean REST API you can call without asking anyone (Open Host Service)</li><li>They have a Slack channel where they take your feature requests and actually act on them (Customer-Supplier) — Their definition of a “Transaction” is still strange, so your developers translate it on the way in (Anticorruption Layer)</li></ul><p>Three patterns. One integration line. This is normal. The goal is not to reduce the stack — the goal is to know what is in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*q3BhTih4BqGP9rJgYWAYiw.png" /></figure><h3>The Architect’s Mandate</h3><p>Count the lines leaving your Bounded Context. If your team has five outgoing dependencies and all five are Conformist, your engineers are spending the majority of their time reacting to other teams breaking their world. Every sprint is a hostage negotiation. Cognitive load is maxed. Burnout is not a risk — it is a schedule.</p><p>Your job as an architect is not to write a faster JSON parser to deal with it. Your job is to take the Context Map into the room where decisions get made and renegotiate the human boundaries.</p><p>Draw a circle around your team. Map your immediate neighbors. Label every line honestly — not how you wish the relationship worked, but how it actually works today. <strong>That map will tell you more about why your last three sprints failed than any retrospective ever will.</strong></p><p>The diagram on the wall shows a system. The Context Map shows the truth. And the truth is the only place worth starting from.</p><h3>The Map is the Conversation</h3><p>The most valuable thing a Context Map produces is not the diagram. It is the argument that happens while you are drawing it.</p><p>When a senior engineer insists a relationship is a Partnership and a junior engineer quietly says it feels more like Conformist — that disagreement is the entire point. You have just surfaced a political reality that has been silently delaying sprints for months.</p><p>Draw the map. Name the relationships. Argue. <strong>You cannot fix what you refuse to see</strong>. ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3378e0b07548" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/your-architecture-diagram-is-lying-to-you-a-practical-guide-to-context-mapping-3378e0b07548">Your Architecture Diagram is Lying to You | A Practical Guide to Context Mapping</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Maps: A Guide to Integration Patterns]]></title>
            <link>https://blog.stackademic.com/context-maps-a-guide-to-integration-patterns-88eb03baeebe?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/88eb03baeebe</guid>
            <category><![CDATA[context-mapping]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[strategic-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 14:37:03 GMT</pubDate>
            <atom:updated>2026-05-18T06:25:04.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*-mOCqczFDy2FJR-6TsN14Q.png" /></figure><p>If you ask ten software engineers to draw the architecture of their system, you will usually get ten variations of the same thing: a chaotic web of boxes and arrows. We draw our microservices, we draw the databases, and we draw lines connecting them.</p><p>But standard architecture diagrams miss the most important variable in software engineering: <strong>Human power dynamics.</strong></p><blockquote>This is where Domain-Driven Design (DDD) and the <strong>Context Map</strong> come in. A Context Map doesn’t just show <em>how</em> systems connect; it shows <em>who holds the power</em> in that connection.</blockquote><p>If you are reading Vaughn Vernon’s legendary work on DDD, you’ll encounter standard “Integration Patterns” that act as the legend for these maps. To make them easier to digest, I like to group them into four real-world categories.</p><h3>Category 1: The “We Are In This Together” Patterns</h3><p>These patterns require high trust, constant communication, and synchronized deployment cycles.</p><ul><li><strong>Partnership:</strong> Imagine two teams in a three-legged race. As Vaughn Vernon’s DDD book defines it, this happens when two bounded contexts will physically <em>succeed or fail together</em>. When your fates are tied, you cannot just throw API specs over the wall. You have to institute a formal process for <strong>coordinated planning and joint management of the integration</strong>. The teams must actively cooperate on how their interfaces evolve to ensure they accommodate the needs of <em>both</em> systems. The golden rule for this pattern is synchronized scheduling: all interdependent features must be planned so they are completed for the same release. <em>(Example: The Checkout Team and the Payment Processing Team jointly evolving their APIs to launch a brand-new payment flow simultaneously).</em></li><li><strong>Shared Kernel:</strong> Sharing part of a model or code creates what the book calls a “very intimate interdependency.” It can be a massive shortcut or completely undermine your system. You must designate an <em>explicit boundary</em> around the exact subset of the domain you agree to share. DDD warns us to “keep the kernel small” and give it “special status” — meaning no team is allowed to change it without explicit consultation with the other. To survive this pattern, you must define a rigorous continuous integration process to keep the code tight and ensure both teams remain perfectly aligned on their Ubiquitous Language. <em>(Example: Two microservices sharing the same Go library for user authentication).</em></li></ul><h3>Category 2: The Upstream/Downstream Power Dynamics</h3><p>In DDD, water flows downstream. The upstream team dictates the rules, and the downstream team has to react. But not all upstream teams are created equal.</p><ul><li><strong>Customer-Supplier Development:</strong> This is a healthy, cooperative Upstream (Supplier) / Downstream (Customer) relationship. As the book notes, even though the upstream team could succeed entirely on their own, they still care about your needs. In this pattern, the downstream team’s priorities actively factor into the upstream team’s planning. If you (Downstream) need a new field in an API, you don’t just hope for the best; you formally <strong>negotiate and budget tasks</strong> together so that everyone understands the exact commitment and release schedule.</li><li><strong>Conformist:</strong> This is the dark side of Upstream/Downstream. The book describes this as a relationship where the upstream team has absolutely no motivation to provide for your needs, leaving you helpless. While individual developers upstream might make altruistic promises to help you, the book brutally warns they are <em>“unlikely to be fulfilled.”</em> To survive, the downstream team gives up on building complex translation layers and just accepts its fate, eliminating complexity by <strong>slavishly adhering</strong> to the upstream team’s model. <em>(Example: Your team integrating with the Stripe or AWS API. Stripe isn’t going to change their API just because you asked.) You are forced to conform.</em></li></ul><h3>Category 3: The Defensive &amp; API Patterns</h3><p>This is how Senior Engineers protect their clean, modern code from messy, external systems.</p><ul><li><strong>Anticorruption Layer (ACL):</strong> This is one of the most powerful concepts in DDD. The book notes that while translation between systems can be elegant when teams are cooperative, <strong>it takes on a <em>“more defensive tone”</em> when you are dealing with messy or uncooperative Upstream systems</strong>. You do not let their messy data models leak into your clean codebase. Instead, you create an <strong>isolating layer</strong> that provides the upstream functionality entirely in terms of your own domain model. It talks to the other system through its existing interface (requiring zero modifications from them), acting as a defensive shield that translates in both directions as necessary.</li><li><strong>Open Host Service (OHS):</strong> Instead of building custom integrations for every single team that wants your data, you define a protocol that gives access to your subsystem as a set of services. You “open” it up so anyone can consume it. The book gives a brilliant warning here: you should expand the protocol for general needs, but if a single downstream team has <em>“idiosyncratic needs,”</em> do not ruin your clean API for them. Use a one-off translator for that special case so your shared protocol stays simple and coherent.</li><li><strong>Published Language:</strong> This almost always goes hand-in-hand with OHS. The translation between two Bounded Contexts requires a common language. Instead of forcing teams to understand your internal database structures, you use a <strong>well-documented shared language</strong> that expresses the necessary domain information as a common medium of communication. <em>(Example: Publishing a clean, standardized JSON or Protobuf schema that all consuming teams translate into and out of).</em></li></ul><h3>Category 4: The “Walk Away” Patterns</h3><p>Sometimes, the best architecture is no architecture at all.</p><ul><li><strong>Separate Ways:</strong> Sometimes, the best architecture is no architecture at all. The book tells us we must be <em>“ruthless when it comes to defining requirements.”</em> Integration is always expensive. If you look at two sets of functionality and realize they have no significant relationship and the benefit of integration is small, you completely cut them loose from each other. You ruthlessly say, “Nope.” The teams go their separate ways, declaring a Bounded Context with absolutely no connection to the others, and find specialized, manual, or simpler solutions within their own small scope.</li><li><strong>Big Ball of Mud:</strong> DDD is incredibly pragmatic. As we survey existing enterprise systems, we inevitably find massive, undocumented legacy systems where models are mixed, and boundaries are entirely inconsistent. The book’s rule here is simple and freeing: <strong>Draw a boundary around the entire mess and do not try to apply sophisticated modeling within it.</strong> Accept that it is a Big Ball of Mud. Your only goal is quarantine — do not let the mud spread to your clean, new microservices. <em>(Pro tip: You usually build an Anticorruption Layer right on the edge of the boundary to safely talk to the Mud!)</em></li></ul><h3>How to use this tomorrow</h3><p>The next time you are tasked with drawing an architecture diagram for your team, don’t try to map the whole company like Google Maps. Draw your service in the center, and map your immediate neighborhood.</p><blockquote><strong>But this time, don’t just draw lines. Label the relationships.</strong></blockquote><p>If you get data from an internal Billing team, ask yourself: <em>“Are they a Customer-Supplier (they listen to our needs) or are we a Conformist (we just take whatever they give us)?”</em> If you have to pull data from an ancient, messy ERP system, draw a line to a “Big Ball of Mud” and explicitly put an <strong>“ACL”</strong> on your side of the line. This visually shows management exactly why you need an extra two weeks to build a translation shield to protect your new service.</p><blockquote>Stop just drawing systems. Start mapping the dynamics that actually dictate how your software gets built.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88eb03baeebe" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/context-maps-a-guide-to-integration-patterns-88eb03baeebe">Context Maps: A Guide to Integration Patterns</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Biggest Misconception About DDD’s Anticorruption Layer]]></title>
            <link>https://umartahir93.medium.com/the-biggest-misconception-about-ddds-anticorruption-layer-7b3a4e16b156?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b3a4e16b156</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[anti-corruption-layer]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 05:00:36 GMT</pubDate>
            <atom:updated>2026-04-10T05:00:36.232Z</atom:updated>
            <content:encoded><![CDATA[<p>If you spend enough time studying Domain-Driven Design (DDD), you will eventually learn about the <strong>Anticorruption Layer (ACL)</strong>.</p><p>Usually, it is introduced alongside every developer’s worst nightmare: the <strong>Big Ball of Mud</strong>. We are taught that when our pristine, modern microservice has to integrate with a chaotic, undocumented, 15-year-old legacy monolith or database, we must build an ACL. It acts as a heavy defensive shield, catching the toxic, messy data, scrubbing it, and translating it into our clean domain models so the “mud” doesn’t spread into our code.</p><p>Because of this, most engineers walk away with a fundamental misconception: <strong>We only need an Anticorruption Layer when the upstream system is garbage</strong>.</p><p>But what happens when the upstream system is beautiful?</p><h4>The Clean API Paradox</h4><p>Imagine you are integrating with an internal team that has done everything right. They have deployed an <strong>Open Host Service (OHS)</strong> with a beautifully documented <strong>Published Language (PL)</strong>. They hand you a pristine, versioned Protobuf or JSON schema. It is a joy to work with.</p><p>If the upstream API is so clean, you don’t need a defensive shield anymore, right? You can just import their schema directly into your core business logic and get to work.</p><blockquote>Wrong. <strong>You still need an Anticorruption Layer.</strong></blockquote><p>To many engineers, this sounds like a contradiction. Why would you build a defensive translation layer to protect yourself from a perfectly clean API?</p><h4>Clean Foreign Data is Still Foreign Data</h4><p>The core philosophy of DDD is strict boundary control. Even if the upstream team’s API is pristine, <strong>their domain model is not your domain model</strong>. Let’s say you are building the Inventory service, and you are consuming data from the Billing team’s beautiful API. To the Billing team, an item is just a line on an invoice. To your Inventory team, an item is a physical box sitting on a shelf in a warehouse.</p><p>If you let the Billing team’s clean JSON schema leak directly into your Inventory business logic, you have just tightly coupled your core system to a foreign domain. If the Billing team decides to release API v2 next year, your core business logic breaks. <strong>You have become a Conformist.</strong></p><h4>The “Elegant” ACL</h4><p>When you place an Anticorruption Layer between your code and a beautiful API, the ACL serves a different purpose. It isn’t a heavy scrubber for toxic mud; it is a lightweight border checkpoint.</p><p>Because the incoming data is already structured by a Published Language, this ACL is incredibly simple. As DDD pioneer Vaughn Vernon notes, translation layers in this scenario are <strong>”simple and elegant</strong>.<strong>”</strong> It might just be a single mapping function that takes the external Billing Item struct and maps it to your internal Inventory Asset struct.</p><p>By writing that one simple mapping function, you achieve total architectural independence. The external API can change, version up, or be replaced entirely, and the only thing in your codebase that needs to be updated is that single elegant translation layer.</p><p>The lesson here is simple: <strong>Do not trust external models, no matter how pretty they look.</strong> A clean foreign model is still a foreign model. Keep your boundaries tight, translate everything at the door, and let your core domain remain entirely your own.</p><h4>The ACL Litmus Test</h4><p>Once you understand this, your Anticorruption Layer actually becomes a diagnostic tool. You can use it as a “litmus test” to instantly measure the health of the system you are integrating with.</p><p>Just open your codebase and look at the ACL you had to write:</p><p><strong>The Simple ACL:</strong> If your translation layer is just a few elegant mapping functions and standard type conversions, congratulations. You are integrating with a <strong>healthy Open Host Service</strong> and a <strong>Published Language</strong>.</p><p><strong>The Beast ACL</strong>: If your translation layer is a massive, complex beast full of regex parsers, null-checks, conditional workarounds, and thousands of lines of defensive code.. you don’t even need to look at the upstream architecture diagram. You already know you are integrating with a <strong>Big Ball of Mud</strong>.</p><p>The next time you integrate with a system, don’t ask yourself if you need an Anticorruption Layer – assume that you do. Instead, let the size and complexity of that layer tell you exactly what kind of neighborhood your code just moved into.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b3a4e16b156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why in DDD Your Domain Model Should Own the Database]]></title>
            <link>https://blog.stackademic.com/why-in-ddd-your-domain-model-should-own-the-database-99aafc37b0da?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/99aafc37b0da</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 16:18:55 GMT</pubDate>
            <atom:updated>2026-03-15T16:18:55.910Z</atom:updated>
            <content:encoded><![CDATA[<p>When developers first learn <strong>Domain-Driven Design (DDD)</strong>, one of the hardest concepts to internalize is the relationship between the <strong>domain model</strong> and the <strong>database</strong>. Many think the database is just a generic storage layer a “bucket of data” that exists independently of the code. I</p><blockquote>In modern DDD, this is <strong>wrong</strong>. The database is not just storage; it is <strong>an extension of your domain model</strong>, the “model at rest.” Let’s break down why this matters and how to do it right.</blockquote><h3>1. Logical vs. Physical: Model vs. Database</h3><p>The first step to understanding this is distinguishing <strong>logical</strong> from <strong>physical</strong>:</p><ul><li><strong>Domain Model (Logical)</strong>: This lives in memory and code. It contains entities, value objects, aggregates, and business rules. This is the “brain” of your bounded context. For example:</li></ul><pre>class BacklogItem {<br>    private String title;<br>    private BusinessPriority businessPriority;<br>}</pre><ul><li><strong>Database Schema (Physical)</strong>: This is how the model persists its state. In DDD, inside a <strong>bounded context</strong>, the schema is not just storage it’s the “memory” of the model:</li></ul><pre>CREATE TABLE backlog_item (<br>    id BIGINT PRIMARY KEY,<br>    title VARCHAR(255),<br>    business_priority VARCHAR(50)<br>);</pre><p>Notice the names reflect the domain model exactly. This is <strong>intentional</strong>, not accidental.</p><blockquote><em>Pro tip: Think of the database as the model </em><strong><em>paused on disk</em></strong><em>. The domain model in code is the movie playing; the database is the DVD snapshot.</em></blockquote><h3>2. Why the Database is Part of the Bounded Context</h3><p>Traditionally, databases were treated as <strong>shared global resources</strong>. Multiple applications would plug in and adapt to whatever table names or structures existed. This is the “database-first” anti-pattern.</p><p><strong>DDD flips this</strong>:</p><ul><li>The database is <strong>private to the bounded context</strong>.</li><li>It exists solely to serve that domain model.</li><li>The same team owns the code, the model, and the schema.</li></ul><p>Why? Because <strong>the model and the database evolve together</strong>. Change the rules in the domain, and you must change the schema. This alignment ensures <strong>conceptual integrity</strong>,<strong> reduces translation overhead</strong>, and enforces the <strong>Ubiquitous Language</strong> principle.</p><h3>3. The Mirror Effect: No Translation</h3><p>When the database is a true extension of the model:</p><ul><li>Column names match property names.</li><li>Table names match entity names.</li><li>Value objects are persisted in a way that mirrors their structure.</li></ul><p>Example:</p><pre>class Money {<br>    private BigDecimal amount;<br>    private String currency;<br>}</pre><p>Becomes in the database:</p><pre>money_amount DECIMAL(10,2),<br>money_currency VARCHAR(3)</pre><p>No “translator” is required between code and storage. The model in memory and the model at rest <strong>speak the same language</strong>.</p><h3>4. Temporal Continuity: Model Life Beyond the CPU</h3><p>The domain model doesn’t die when the CPU stops running your code. Without the database:</p><ul><li>You have no history of past states.</li><li>You cannot enforce business rules across time.</li></ul><p>With the database as an extension:</p><ul><li>Relationships (foreign keys, constraints) preserve invariants.</li><li>Data remains consistent with the business logic.</li><li>The model’s rules continue to exist “at rest.”</li></ul><h3>5. Ownership and Protection of the Truth</h3><p>If the database schema is extension of the model:</p><ul><li>Only the domain model should modify it.</li><li>Direct external updates (scripts, other services) break the model’s invariants.</li></ul><p>✅ Correct: External systems call your <strong>API</strong>, which executes domain logic and updates the database.</p><p>❌ Wrong: Another team or script updates tables directly.</p><p>Ownership ensures <strong>the database reflects reality as dictated by the domain model</strong>.</p><h3>6. Co-Evolution: Code and Schema Move Together</h3><p>A “pro-level” DDD system treats <strong>domain model and schema as a single organism</strong>:</p><ul><li>Add a new feature → update the domain model</li><li>Update the database schema to match</li><li>Update APIs for external interaction</li></ul><p>Example: A new rule allows a user to have multiple phone numbers:</p><ul><li>Domain model: List&lt;PhoneNumber&gt; in User entity</li><li>Database: New table user_phone_number</li><li>API: Return all phone numbers in user object</li></ul><p>The schema <strong>never lags behind the model</strong>, and migrations are part of the same change set (not necessarily one PR).</p><h3>7. Practical Implications</h3><ul><li><strong>Value Objects</strong>: Persist each field explicitly. No flattening unless it matches your model.</li><li><strong>Aggregates</strong>: Table structures should reflect aggregate boundaries.</li><li><strong>Microservices</strong>: Each service owns its own database. Shared databases break bounded contexts.</li></ul><h3>8. Summary</h3><ul><li><strong>The domain model is the brain.</strong></li><li><strong>The database is the memory.</strong></li><li><strong>The schema is the model at rest.</strong></li><li><strong>Ownership ensures invariants and alignment.</strong></li><li><strong>Code and schema co-evolve.</strong></li></ul><p>Treating the database as an extension of the domain model removes translation overhead, enforces Ubiquitous Language, and keeps your bounded contexts clean.</p><blockquote><em>In DDD, the database is no longer just a “storage tool” it is the persistence mirror of the model and a full participant in the bounded context.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99aafc37b0da" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-in-ddd-your-domain-model-should-own-the-database-99aafc37b0da">Why in DDD Your Domain Model Should Own the Database</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Just Handle Errors, Return Them: A Guide to Idiomatic Go]]></title>
            <link>https://umartahir93.medium.com/dont-just-handle-errors-return-them-a-guide-to-idiomatic-go-d8ab617cc814?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ab617cc814</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 20:55:22 GMT</pubDate>
            <atom:updated>2025-07-12T20:55:22.193Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Go, error handling isn’t just a feature; it’s a core design philosophy. While many languages use exceptions to manage failure, Go takes a simpler, more explicit approach guided by a single, powerful proverb: <strong>“Errors are values.”</strong></p><p>Understanding this principle is the key to moving from writing code that simply works to writing code that is clean, reusable, and truly idiomatic.</p><p>Let’s explore how this philosophy shapes the way we write code, where we should handle errors, and when we should simply pass them on.</p><h3>The Golden Rule: Errors Are Values</h3><p>In Go, an error is just an interface type. This means an error can be returned from a function just like any other value, such as an int or a string. This design choice has a profound impact: it encourages—and almost forces—you to be deliberate about how you handle failure.</p><p>Instead of a try-catch block that interrupts the normal flow of your program, Go uses a simple if err != nil check. This pattern keeps error handling as a visible and explicit part of your code&#39;s control flow.</p><p>The immediate consequence of this design is that <strong>functions should not take side effects they weren’t asked to.</strong> <strong>A function’s job is to perform its task and report its outcome</strong>. If it fails, it should package the problem into an error value and return it to its caller.</p><h3>The Anti-Pattern: Logging Inside a Function</h3><p>A common mistake for developers new to Go is to log an error inside the function where it occurred. Consider this example:</p><pre>// anti-pattern.go</pre><pre>func createUser(name string) {<br>    if name == &quot;&quot; {<br>        // This function is taking on too much responsibility.<br>        log.Printf(&quot;ERROR: user name cannot be empty&quot;)<br>        return<br>    }<br>    // ... logic to create user<br>}</pre><pre>func handleRequest() {<br>    // The caller has no idea that createUser failed.<br>    createUser(&quot;&quot;) <br>}</pre><p>This creates several problems:</p><ol><li><strong>Loss of Context:</strong> The createUser function doesn&#39;t know <em>why</em> it was called. The caller (e.g., an HTTP handler) has much more context and can provide a more informative log message.</li><li><strong>Reduced Reusability:</strong> What if another part of your application needs to call createUser but wants to handle the error differently, like showing it in a UI? The caller has no way of knowing the function failed.</li><li><strong>Inconsistent Logging:</strong> Different functions might log with different formats or levels, leading to messy and un-parsable logs.</li></ol><h3>The Idiomatic Way: Return the Error</h3><p>The correct approach is to have the function return the error value. This separates the concern of performing the task from the concern of handling its failure.</p><pre>// idiomatic.go</pre><pre>func createUser(name string) error {<br>    if name == &quot;&quot; {<br>        // Return the error as a value.<br>        return errors.New(&quot;user name cannot be empty&quot;)<br>    }<br>    // ... logic to create user<br>    return nil<br>}</pre><pre>func handleRequest() {<br>    err := createUser(&quot;&quot;)<br>    if err != nil {<br>        // The caller decides what to do.<br>        log.Printf(&quot;ERROR: failed to handle request: %v&quot;, err)<br>        // ...<br>    }<br>}</pre><p>This is clean, testable, and reusable. The createUser function can now be used in any context, and the caller always has full control over the outcome.</p><h3>Knowing When to Stop: Handling Errors at the Boundary</h3><p>This leads to the ultimate question: if every function returns an error to its caller, where does it stop?</p><p>You stop propagating an error at the <strong>boundary of a logical unit of work</strong>. This is the point where your application needs to make a decision and translate the internal error into a final outcome for the outside world.</p><p>Here are the most common boundaries:</p><h4>1. In an HTTP Handler</h4><p>An HTTP handler’s job is to translate a request into a response. It’s the perfect place to handle an error. You catch the error from your service layer, log the full, detailed error for your own debugging, and return a simple, user-friendly HTTP response.</p><pre>func (h *Handler) HandleUpdateProfile(w http.ResponseWriter, r *http.Request) {<br>    err := h.service.UpdateProfile(ctx, userData)   <br> // --- THIS IS THE BOUNDARY ---<br>    if err != nil {<br>        // Log the detailed error for your team.<br>        log.Printf(&quot;ERROR: failed to update profile: %v&quot;, err)<br>// Respond to the user with a simple, safe message.<br>        http.Error(w, &quot;Something went wrong&quot;, http.StatusInternalServerError)<br>        return // Stop processing.<br>    }<br>    w.WriteHeader(http.StatusOK)<br>}</pre><h4>2. In a Background Worker</h4><p>For a message queue consumer, the “unit of work” is processing a single message. Here, you catch the error, log it, and then decide what to do with the message — should it be retried, or sent to a Dead-Letter Queue (DLQ)?</p><pre>func (w *Worker) ProcessImageJob(msg Message) {<br>    err := w.imageService.Resize(msg.ImageURL)<br>// --- THIS IS THE BOUNDARY ---<br>    if err != nil {<br>        // Log the detailed error.<br>        log.Printf(&quot;ERROR: failed to process image job %s: %v&quot;, msg.ID, err)<br>        <br>        // Acknowledge the message so it doesn&#39;t get retried forever.<br>        // Or, you could return an error to your message queue library<br>        // to signal a retry is needed.<br>    }<br>}</pre><h4>3. In the main() function of a CLI Tool</h4><p>For a command-line app, the main function is the ultimate boundary. You catch the error from your application&#39;s main Run function, print a user-friendly error to stderr, and exit with a non-zero status code to signal failure.</p><pre>func main() {<br>    if err := app.Run(os.Args); err != nil {<br>        // --- THIS IS THE BOUNDARY ---<br>        fmt.Fprintf(os.Stderr, &quot;Error: %v\n&quot;, err)<br>        os.Exit(1) // Exit with a failure code.<br>    }<br>}</pre><p>By embracing the <strong>“errors are values”</strong> philosophy and handling them at these logical boundaries, you can write Go code that is not only robust and reliable but also a pleasure to read and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ab617cc814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Isolation Levels in Databases]]></title>
            <link>https://umartahir93.medium.com/understanding-isolation-levels-in-databases-f6eac51705e0?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6eac51705e0</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[acid]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 13:41:06 GMT</pubDate>
            <atom:updated>2025-03-15T13:41:06.449Z</atom:updated>
            <content:encoded><![CDATA[<p>When dealing with transactions in a database, <strong>isolation levels</strong> determine how concurrent transactions interact with each other. The need for various isolation levels arises due to <strong>read phenomena</strong> such as <a href="https://umartahir93.medium.com/understanding-dirty-reads-in-postgresql-and-how-to-see-them-31be2a560ce4">dirty reads</a>, <a href="https://umartahir93.medium.com/understanding-non-repeatable-reads-in-postgresql-31a3906d5cd2">non-repeatable reads</a>, <a href="https://umartahir93.medium.com/understanding-phantom-reads-in-postgresql-a4b6cc1c8acd">phantom reads</a> and <a href="https://umartahir93.medium.com/cf76c7570bfa">lost updates</a>. Each isolation level offers a different tradeoff between consistency and performance.</p><h3>Setting Isolation Levels</h3><p>Databases allow you to set the isolation level when starting a transaction using SQL commands like:</p><pre>SET TRANSACTION ISOLATION LEVEL READ COMMITTED;</pre><p>Now, let’s explore the different isolation levels and their impact on data consistency.</p><h3>1. Read Uncommitted</h3><p>This is the lowest level of isolation, where transactions can read <strong>uncommitted changes</strong> from other transactions. This means:</p><ul><li>Other transactions’ uncommitted data is visible.</li><li><strong>Dirty reads</strong> are possible (reading uncommitted changes that may later be rolled back).</li><li><strong>Fastest</strong> isolation level but highly inconsistent.</li></ul><blockquote><em>Supported primarily by SQL Server; most databases avoid it due to its risks.</em></blockquote><h3>Example</h3><p>Transaction A updates a row but hasn’t committed yet. Transaction B reads this uncommitted data. If Transaction A rolls back, Transaction B would have read <strong>incorrect data</strong>.</p><h3>2. Read Committed</h3><p>A widely used isolation level that ensures transactions only read <strong>committed changes</strong>.</p><ul><li><strong>No dirty reads</strong> (a transaction only sees committed data).</li><li><strong>Non-repeatable reads</strong> are possible (data read once might change if read again).</li><li>Default in many databases (e.g., PostgreSQL, Oracle, MySQL InnoDB).</li></ul><h3>Example</h3><p>Transaction A reads a row. Meanwhile, Transaction B updates and commits changes to the same row. If Transaction A reads it again, it sees the updated value (leading to <strong>non-repeatable reads</strong>).</p><h3>3. Repeatable Read</h3><p>This isolation level prevents <strong>dirty reads, non-repeatable reads and lost updates anomalies </strong>ensuring:</p><ul><li>Once a row is read in a transaction, it <strong>remains unchanged</strong> throughout the transaction.</li><li><a href="https://umartahir93.medium.com/understanding-phantom-reads-in-postgresql-a4b6cc1c8acd"><strong>Phantom reads</strong></a> (new rows appearing) are still possible.</li><li>PostgreSQL implements this as <strong>snapshot isolation</strong>.</li></ul><h3>Example</h3><p>Transaction A reads a row multiple times while another transaction updates it. The value remains the same for Transaction A. However, new rows inserted by another transaction <strong>may</strong> still be visible.</p><h3>4. Snapshot Isolation</h3><p>A variant of <strong>Repeatable Read</strong>, <strong>Snapshot Isolation</strong> takes a <strong>consistent snapshot</strong> of the database at the start of a transaction.</p><ul><li>Each transaction reads from a snapshot, ignoring changes made by others after it starts.</li><li>Prevents <strong>phantom reads</strong> and ensures consistent queries.</li><li>Used by PostgreSQL’s <strong>Repeatable Read</strong> mode.</li></ul><h3>Example</h3><p>If Transaction A starts at <strong>10:00 AM</strong>, it continues to see the database <strong>as it was at that time</strong>, even if new rows are inserted afterward by another transaction.</p><h3>5. Serializable</h3><p>The strictest isolation level, treating transactions as if they are <strong>executed sequentially</strong>.</p><ul><li>Prevents <strong>all</strong> read anomalies (dirty reads, non-repeatable reads, phantom reads, lost updates).</li><li>Ensures the highest data consistency but at the cost of <strong>performance</strong>.</li><li>Uses <strong>locking</strong> or <strong>serialization</strong> techniques to enforce strict isolation.</li></ul><h3>Example</h3><p>If multiple transactions attempt to modify the same data, they are executed <strong>one after the other</strong>, ensuring absolute consistency but leading to potential slowdowns.</p><h3>Comparison of Isolation Levels</h3><p>The table below summarises which anomalies each isolation level prevents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*FNamEzr-cDuphtBq.png" /></figure><h3>Final Thoughts</h3><p>Choosing an isolation level depends on the <strong>tradeoff between consistency and performance</strong>. Many databases default to <strong>Read Committed</strong> because it balances <strong>data integrity and speed</strong>. However, applications requiring <strong>strict consistency</strong> (e.g., banking systems) often use <strong>Serializable</strong> or <strong>Snapshot Isolation</strong>.</p><p>Understanding isolation levels is crucial when designing a database system that requires efficient concurrency management without compromising consistency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6eac51705e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Lost Updates in PostgreSQL]]></title>
            <link>https://umartahir93.medium.com/understanding-lost-updates-in-postgresql-cf76c7570bfa?source=rss-228101f85f71------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf76c7570bfa</guid>
            <category><![CDATA[lost-update]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[locking]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Umar Tahir]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 12:21:56 GMT</pubDate>
            <atom:updated>2025-03-15T12:57:39.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Lost updates are a common concurrency issue in databases where multiple transactions read and modify the same data, but one transaction’s update gets overwritten by another. This results in unintended data loss and inconsistencies.</p><h3>What is a Lost Update?</h3><p>A <strong>lost update</strong> occurs when two or more transactions read the same value, modify it, and then update the database. The last transaction to commit <strong>overwrites</strong> the changes made by the earlier transaction(s), leading to data loss.</p><h3>Example Scenario</h3><p>Consider an e-commerce application where two users are updating the inventory for a product simultaneously. If both users read the current stock value and update it without proper transaction control, one of their updates may be lost.</p><h3>Demonstrating Lost Updates in PostgreSQL</h3><p>By default, PostgreSQL operates at the <strong>Read Committed</strong> isolation level, which does not prevent lost updates. Let’s see it in action.</p><h3>Step 1: Setup the Table and Insert Some Data</h3><pre>CREATE TABLE inventory (<br>    product_id SERIAL PRIMARY KEY,<br>    stock INT<br>);</pre><pre>INSERT INTO inventory (stock) VALUES (10);</pre><h3>Step 2: Open Transaction A and Read the Stock Value</h3><p>Open <strong>Transaction A</strong> and retrieve the current stock value.</p><pre>BEGIN;<br>SELECT stock FROM inventory WHERE product_id = 1; -- Returns 10</pre><h3>Step 3: Open Transaction B and Read the Same Stock Value</h3><p>In another session, open <strong>Transaction B</strong> and retrieve the same stock value.</p><pre>BEGIN;<br>SELECT stock FROM inventory WHERE product_id = 1; -- Also returns 10</pre><h3>Step 4: Both Transactions Update the Stock</h3><p><strong>Transaction A</strong> reduces stock by 2 and updates it.</p><pre>UPDATE inventory SET stock = 8 WHERE product_id = 1;<br>COMMIT;</pre><p><strong>Transaction B</strong> also reduces stock by 2, based on the old value (10), and updates it.</p><pre>UPDATE inventory SET stock = 8 WHERE product_id = 1;<br>COMMIT;</pre><h3>Step 5: Check the Final Stock Value</h3><pre>SELECT stock FROM inventory WHERE product_id = 1; -- Still 8 instead of 6!</pre><p>The update from <strong>Transaction A</strong> was <strong>lost</strong> because <strong>Transaction B</strong> overwrote it without considering the prior update.</p><h3>How to Prevent Lost Updates</h3><p>Lost updates can be prevented using <strong>proper concurrency control mechanisms</strong>:</p><h3>1. Using SELECT … FOR UPDATE (Pessimistic Locking)</h3><pre>BEGIN;<br>SELECT stock FROM inventory WHERE product_id = 1 FOR UPDATE;<br>UPDATE inventory SET stock = stock - 2 WHERE product_id = 1;<br>COMMIT;</pre><p>This locks the row, ensuring no other transaction can modify it until the first transaction is complete.</p><h3>2. Using Optimistic Locking with Versioning</h3><p>Add a version column to track updates:</p><pre>ALTER TABLE inventory ADD COLUMN version INT DEFAULT 1;</pre><p>Modify updates to check the version before committing:</p><pre>UPDATE inventory SET stock = stock - 2, version = version + 1 WHERE product_id = 1 AND version = &lt;old_version&gt;;</pre><p>If the version doesn’t match, the update fails, preventing lost updates.</p><h3>3. Using Repeatable Read (Or Serializable) Isolation Levels</h3><pre><br>BEGIN TRANSACTION ISOLATION LEVEL Repeatable Read;<br><br>-- Step 1: Read the current stock to establish a shared lock<br>SELECT stock FROM inventory WHERE product_id = 1;<br><br>-- Step 2: Update the stock<br>UPDATE inventory SET stock = stock - 2 WHERE product_id = 1;<br><br>COMMIT;</pre><p>This prevents lost updates but potentially reducing performance due to strict locking.</p><h3>Conclusion</h3><p>Lost updates occur when concurrent transactions overwrite each other’s changes. This can lead to incorrect data and business logic failures. Using techniques like <strong>SELECT … FOR UPDATE</strong>, <strong>optimistic locking</strong>, <strong>Repeatable isolation or Serializable isolation</strong> helps ensure data consistency while balancing performance needs.</p><p>Understanding and handling lost updates is crucial for designing reliable database systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf76c7570bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>