<?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 Mohamed Lotfy on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Lotfy on Medium]]></description>
        <link>https://medium.com/@mhmdlotfy9?source=rss-656e1a5d2427------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4zoH51oQP9QHzzvVM7kc9Q.jpeg</url>
            <title>Stories by Mohamed Lotfy on Medium</title>
            <link>https://medium.com/@mhmdlotfy9?source=rss-656e1a5d2427------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:38:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mhmdlotfy9/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[⚡️ Supercharge Microservices with Materialized Views: Solve the DB Per Service problem ⚡️]]></title>
            <link>https://medium.com/@mhmdlotfy9/%EF%B8%8F-supercharge-microservices-with-materialized-views-solve-the-db-per-service-problem-%EF%B8%8F-8937efe9b7f8?source=rss-656e1a5d2427------2</link>
            <guid isPermaLink="false">https://medium.com/p/8937efe9b7f8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[materializedviews]]></category>
            <category><![CDATA[query]]></category>
            <dc:creator><![CDATA[Mohamed Lotfy]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 07:42:50 GMT</pubDate>
            <atom:updated>2025-09-18T12:12:21.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><ul><li>For microservices, feed an aggregated DB read, build MVs that match each UI read shape, and refresh on a cadence or via batched events.</li><li>The Materialized View pattern describes <strong>generating prepopulated views of data</strong> in environments where the source data isn’t in a suitable format for querying</li></ul><h3>1) What is the Materialized-View pattern?</h3><p>A materialized view is a saved query result that is stored as a real table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j1-SEm4jdAY1Yl4v.png" /></figure><p>Instead of <strong>recomputing joins and aggregates</strong> on every request, you read precomputed rows</p><p>This makes read queries much faster for heavy shapes (dashboards, enriched API responses)</p><h3>2) What problem does it fix?</h3><p><strong>In microservices</strong>, you often see this pattern:</p><ul><li>Each service owns its own data (<strong>DB per service</strong>).</li><li>The frontend needs an enriched read (joins <strong>Catalog, Pricing, Cart)</strong>.</li><li>Doing those joins live is slow and couples services; duplicating logic in each service is brittle.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*7pr5tXQrhgzvPg4m6-5jAQ.png" /></figure><p>Materialized Views let you precompute the enriched read model in a central read DB. Services keep owning writes. <br>The read DB serves fast queries. This reduces latency, centralizes complex joins, and avoids repeated expensive queries.</p><h4><strong>3) Syntax — PostgreSQL</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*a-iFSJY3GegC1UtRCI2r1g.png" /><figcaption>PostgreSQL (correct, simple) — full form and management:</figcaption></figure><pre>-- create and populate immediately (default)<br>    CREATE MATERIALIZED VIEW mv_name AS<br>    SELECT …<br>    FROM …<br>    WHERE …;<br><br>-- create without populating (use when you want indexes first)<br>    CREATE MATERIALIZED VIEW mv_name AS<br>    SELECT …<br>    FROM …<br>    WHERE …<br>    WITH NO DATA;<br><br>-- refresh (full)<br>    REFRESH MATERIALIZED VIEW mv_name;<br><br>-- refresh without blocking reads (requires unique index)<br>    REFRESH MATERIALIZED VIEW CONCURRENTLY mv_name;</pre><p><strong>Important:</strong> CONCURRENTLY requires a unique index on the materialized view and cannot run inside a transaction.</p><h3>3) Key benefits</h3><ul><li><strong>Low-latency reads</strong> for heavy queries.</li><li><strong>Centralized query logic</strong> — one place holds the expensive join/aggregate.</li><li><strong>Lower OLTP load</strong> — fewer repeated joins on hot tables.</li><li><strong>Flexible refresh strategy</strong> — schedule or batch updates to balance freshness vs cost.</li></ul><h3>4) Key considerations</h3><ul><li><strong>Staleness</strong> — MV shows data as of the last refresh.</li><li><strong>Refresh cost</strong> — a full refresh can be expensive. CONCURRENTLY helps read but still computes.</li><li><strong>Storage</strong> — MVs use disk and indexes</li><li><strong>Operational complexity</strong> — track dependencies and refresh cadence.</li></ul><h3>5) Example: Shopping Cart + Catalog + Pricing</h3><h4>Scenario</h4><ul><li><strong>Catalog</strong> owns product_id, title, available.</li><li><strong>Pricing</strong> owns product_id, price_cents, currency.</li><li><strong>Shopping Cart</strong> owns cart_id, user_id, product_id, quantity.<br>User adds an item to cart; the UI must show title, availability, price, line total, and cart total — fast.</li></ul><h4>Challenges</h4><ul><li>Live joins across services or DBs: slow and tightly coupled.</li><li>You must keep writes owned by services and still serve fast reads.</li></ul><h4>Solution (Materialized-View pattern)</h4><ol><li>Each service emits domain events (ProductUpdated, PriceChanged, CartItemAdded).</li><li>A <strong>materializer</strong> consumes events and upserts them into the central read_ tables in a read DB.</li><li>Create a shopping_cart_view materialized view that joins read_cart_items, read_products, and read_prices.</li><li>Refresh the MV in batches or on a cadence (or update denormalized read tables for per-cart real-time needs).</li></ol><h3>Event-driven flow (step-by-step)</h3><ol><li><strong>User</strong> clicks Add → Frontend calls <strong>Shopping Cart</strong> service.</li><li><strong>Shopping Cart</strong> writes to its DB and emits CartItemAdded { cart_id, user_id, product_id, quantity, ts }.</li><li><strong>Materializer worker</strong> consumes events and upserts into read_cart_items</li><li>Materializer batches events</li></ol><p><strong>for scale</strong>: update a denormalized cart_read table per cart and avoid full MV refreshes.</p><h3>Full example: SQL + flow</h3><h4>Read tables (DDL)</h4><pre>CREATE TABLE read_products (<br>  product_id uuid PRIMARY KEY,<br>  title text NOT NULL,<br>  available boolean NOT NULL,<br>  updated_at timestamptz NOT NULL<br>);<br>CREATE TABLE read_prices (<br>  product_id uuid PRIMARY KEY,<br>  price_cents bigint NOT NULL,<br>  currency text NOT NULL,<br>  updated_at timestamptz NOT NULL<br>);<br>CREATE TABLE read_cart_items (<br>  cart_id uuid NOT NULL,<br>  user_id uuid NOT NULL,<br>  product_id uuid NOT NULL,<br>  quantity int NOT NULL,<br>  added_at timestamptz NOT NULL,<br>  PRIMARY KEY (cart_id, product_id)<br>);</pre><h4>Materialized view (create with no data, add indexes first)</h4><pre>CREATE MATERIALIZED VIEW shopping_cart_view AS<br>SELECT<br>  c.cart_id,<br>  c.user_id,<br>  c.product_id,<br>  p.title,<br>  p.available,<br>  pr.price_cents,<br>  c.quantity,<br>  (pr.price_cents * c.quantity) AS line_total_cents<br>FROM read_cart_items c<br>LEFT JOIN read_products p  ON p.product_id = c.product_id<br>LEFT JOIN read_prices   pr ON pr.product_id = c.product_id<br>WITH NO DATA;</pre><h4>Indexes (required for CONCURRENTLY + speed)</h4><pre>CREATE UNIQUE INDEX shopping_cart_view_pk<br>  ON shopping_cart_view (cart_id, product_id);</pre><pre>CREATE INDEX idx_read_cart_items_cart ON read_cart_items (cart_id);<br>CREATE INDEX idx_read_products_updated_at ON read_products (updated_at);<br>CREATE INDEX idx_read_prices_updated_at ON read_prices (updated_at);</pre><h4>Populate the MV</h4><pre>REFRESH MATERIALIZED VIEW CONCURRENTLY shopping_cart_view;</pre><h4>Read example (fast)</h4><pre>SELECT cart_id, product_id, title, available, price_cents, quantity, line_total_cents<br>FROM shopping_cart_view<br>WHERE cart_id = &#39;...&#39;;</pre><h3>6) Views vs Materialized Views (quick)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*l2ufa4Xe4b0MdEdI_yRssA.png" /></figure><h3>Summary</h3><p>Materialized Views let you precompute expensive joins and aggregates in Postgres so microservices can serve fast, consistent reads without heavy cross-service joins.</p><p>In a Shopping Cart example, services emit events, a materializer builds read tables, and a shopping_cart_view materialized view joins product, price and cart data for the UI. Refresh the MV with REFRESH MATERIALIZED VIEW CONCURRENTLY on a cadence or batch updates to balance freshness and cost.</p><p>This keeps services decoupled, reduces latency, and centralizes complex query logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8937efe9b7f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>