<?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 Mohd Amaan on Medium]]></title>
        <description><![CDATA[Stories by Mohd Amaan on Medium]]></description>
        <link>https://medium.com/@amaan2000mohd?source=rss-c6be102fe838------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uB-fbfVp1yaThS68</url>
            <title>Stories by Mohd Amaan on Medium</title>
            <link>https://medium.com/@amaan2000mohd?source=rss-c6be102fe838------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:30:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amaan2000mohd/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[Optimistic vs Pessimistic Locking]]></title>
            <link>https://medium.com/@amaan2000mohd/optimistic-vs-pessimistic-locking-09c92229614d?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/09c92229614d</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[locking]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 06:19:53 GMT</pubDate>
            <atom:updated>2026-10-22T06:19:53.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>The anomaly we’re actually preventing</h3><p>Every concurrency strategy is a trade between <strong>waiting</strong> and <strong>retrying</strong>. Both locking styles exist to stop one anomaly: the <strong>lost update</strong>, where two read-modify-write cycles interleave and the later commit silently discards the earlier one.</p><p>Don’t assume your isolation level covers you. READ COMMITTED, the default in Postgres, Oracle and SQL Server, allows it. So does MySQL’s REPEATABLE READ for plain (non-locking) reads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVexr8W3FbNLe1wtJ0m8EQ.png" /></figure><p><strong>Pessimistic</strong> control serializes access up front and pays in latency and throughput. <strong>Optimistic</strong> control lets everyone proceed and pays in rejected work. The real design question is which cost your system absorbs better, and at which tier you enforce the guard.</p><h3>Pessimistic locking: serialize at the resource</h3><p>Take an exclusive row lock before reading and hold it until commit. Correctness comes from the database’s lock manager, so the guarantee is exactly as wide as one database’s transaction boundary, and no wider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fD5atMOFdoIf03KFCNNhmA.png" /></figure><pre>BEGIN;<br>SELECT stock FROM inventory WHERE id = 42 FOR UPDATE;  -- row is now yours<br>UPDATE inventory SET stock = stock - 1 WHERE id = 42;<br>COMMIT;</pre><p><strong>Design notes</strong></p><ul><li><strong>Bound the wait.</strong> Set lock_timeout (Postgres) or innodb_lock_wait_timeout (MySQL), or use NOWAIT to fail fast. An unbounded wait turns one hot row into thread-pool exhaustion.</li><li><strong>Order your locks.</strong> Deadlocks come from two transactions taking the same rows in different orders. Lock by primary key, ascending, every time.</li><li><strong>SKIP LOCKED for work queues.</strong> Workers claim the next free job instead of queuing behind each other.</li><li><strong>Never span I/O.</strong> No HTTP call, message publish or user think time inside the transaction. Lock hold time is your throughput ceiling on that row.</li></ul><h3>Optimistic locking: validate at commit</h3><p>No locks are held. Each row carries a monotonic version, and the write is a compare-and-set that succeeds only if the version is unchanged. Correctness lives in the write predicate, which is why this pattern stretches across process and network boundaries where locks can&#39;t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o44LqwXKTkY7H1ks7KvmVg.png" /></figure><pre>UPDATE inventory<br>SET    stock = stock - 1, version = version + 1<br>WHERE  id = 42 AND version = 1;<br>-- 0 rows affected? Someone beat you. Re-read and retry.</pre><p><strong>Design notes</strong></p><ul><li><strong>Same pattern at every tier.</strong> HTTP: ETag + If-Match, answered with 412 Precondition Failed. DynamoDB: ConditionExpression. JPA/Hibernate: @Version. Postgres SERIALIZABLE is the same idea done by the engine.</li><li><strong>Retries need a budget.</strong> Cap attempts, add jittered backoff, then surface the conflict to the caller. Unbounded retries under contention become a retry storm.</li><li><strong>Retry the intent, not the payload.</strong> Re-read, re-apply the business operation, re-validate. Replaying the stale request body just re-creates the lost update.</li><li><strong>Use an integer version, not </strong><strong>updated_at.</strong> Clock resolution and skew can give two writes the same timestamp and let a stale write pass.</li></ul><h3>Where the guard lives in a distributed system</h3><p>The database lock is the easy case. Once a write crosses a service boundary, there is no shared transaction to hold a lock in, and the choice of tier matters more than the choice of style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX68eLRFS-MkbFzhVsi5xg.png" /></figure><p>The bottom row is the one that bites. A Redis or etcd lease expires on a clock, and a holder hit by a GC pause or network partition will keep writing after it lost the lease. The fix is a <strong>fencing token</strong>: a number that increases with every grant, which the storage layer compares and rejects if it’s older than one it has already seen.</p><h3>The two questions that decide it</h3><p>Ask how often writers collide, and how painful a failed write is. The answer drops you into one box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySNfyBFgSAO78oCa_J9yFA.png" /></figure><p>Most apps live in the bottom-left. Default to optimistic and earn your way to locks.</p><h3>The flowchart to keep on your desk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOA_we0KPl-jvNd89hhXvw.png" /></figure><p>Notice the first question. Many “locking” problems vanish when the read-modify-write becomes one atomic statement.</p><h3>Side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr45n8eGXPmFji29EVfl7w.png" /></figure><h3>Measure before you switch</h3><p>Don’t change strategy on intuition. These four signals tell you which cost you’re actually paying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHaU0Bbi4aFHw7iyf_dGmw.png" /></figure><h3>The takeaway</h3><p>Default to optimistic, enforce it at the outermost tier that owns the data, and move a specific hot path to pessimistic only when the metrics above say retries cost more than waiting.</p><p>But treat heavy contention as a <strong>data-model smell</strong>, not a locking problem. Before choosing a lock, ask whether the hot row can be:</p><ul><li><strong>Split</strong>, as sharded counters summed on read</li><li><strong>Made append-only</strong>, as a ledger of reservations instead of one mutable balance</li><li><strong>Owned by one writer</strong>, by partitioning a queue on the entity key so writes to it are serial by design</li></ul><p>Locks manage contention. Good data models remove it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09c92229614d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s actually inside an Apache Iceberg table?]]></title>
            <link>https://medium.com/@amaan2000mohd/whats-actually-inside-an-apache-iceberg-table-a9b38f0e085b?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b38f0e085b</guid>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 13:20:48 GMT</pubDate>
            <atom:updated>2026-10-16T13:20:48.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>A table that is really a tree</h3><p>An Apache Iceberg table behaves like one ordinary table when you query it. On disk, it is a small tree of immutable files: one JSON file on top, two layers of Avro files in the middle, and Parquet files at the bottom.</p><p>Most of the time you never need to see that tree. But when a query reads too many files, a table slows down over time, or row counts look wrong, the answer is almost always somewhere in those layers.</p><p>This post walks through each layer with one tiny example table, then traces two real queries through the tree to show exactly which files get opened and which get skipped. It is based on the DuckDB team’s deep dive, <a href="https://duckdb.org/2026/10/13/inside-iceberg-table.html">What Is Inside an Iceberg Table?</a>, which uses DuckDB’s SQL to read every layer directly.</p><h3>The big picture</h3><p>Every layer points to the files in the layer below it. A query always starts at the top and only goes as deep as it has to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*V_KwuzdCxHH2j5s-heHoGw.png" /></figure><p>To make this concrete, the rest of this post uses one small table of train services, partitioned by date, changed three times:</p><pre>CREATE TABLE lake.demo.services (<br>  service_id BIGINT, service_date DATE, station VARCHAR, delay_min INTEGER<br>) PARTITIONED BY (service_date);<br><br>-- 1. Insert 9,000 rows spread round-robin over Oct 1, 2 and 3<br>-- 2. Insert 3,000 rows for Oct 4<br>-- 3. Delete the 1,000 Oct 2 rows with a 4-minute delay</pre><p>The table ends with 11,000 rows and three snapshots, one per change.</p><h3>Layer 0 and 1: the catalog and the metadata file</h3><p>The catalog holds exactly one piece of mutable state per table: a pointer to the current metadata file. Everything below that pointer is immutable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*5rAzPJKU6mh4DP3PicMWDg.png" /></figure><p>Note the last box: after the delete, the table still reports 12,000 records and four data files. The delete rewrote nothing; it added one delete file.</p><p>Two cautions. The Iceberg spec makes these summary fields optional, so a table written by another engine may show some of them as empty; treat them as a hint, not a guarantee. And the metadata file grows with every commit, so a table with thousands of small commits can become slow to load until you expire old snapshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*K63Jk72T-U5SI7sxqTSPXg.png" /></figure><p>Until the pointer moves, readers keep seeing the old version, so nobody ever reads a half-written table.</p><h3>Layer 2: the manifest list, or the labels on the boxes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*5q-d59UCjXmhInbuJTMYmg.png" /></figure><p>Think of a warehouse full of boxes. The manifest list is the label stuck on the outside of each box. You read the labels first and only open the boxes that could match.</p><p>Every snapshot points to exactly one manifest list, an Avro file with one row per manifest. It never lists data files. Here is the manifest list of the latest snapshot in our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*cRW143t7GIz7gTSe1JBmUw.png" /></figure><p>Snapshot 3 still lists manifests A and B from the earlier writes: immutable files get reused, not rewritten. Writing one manifest per commit keeps writes cheap, but many small commits leave readers a long list to scan.</p><h3>Layer 3: the manifests, or the packing slip inside each box</h3><p>Once a box is open, the manifest is the packing slip inside it. It lists every file in that box, one entry per file, with enough detail to decide whether the file is worth reading.</p><p>Across the three manifests in our example there are five entries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*f3dG7A1DNjbN4U6KGANW4A.png" /></figure><p>The column bounds are the second line of defence. They let a reader skip files when you filter on a column that is not the partition column. A query for service_id &gt; 10000 only needs the Oct 4 file, because the bounds of the other three rule them out.</p><p>Notice how useless the first three ranges are. Rows were spread across the days round-robin, so each file holds IDs from almost the whole range and almost any ID filter has to open all three. Data written in the order of a commonly filtered column gets tight bounds, and tight bounds mean more skipping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*lGGDGGevL_G1Y0A33CHrig.png" /></figure><p>The manifest list’s labels rule out A and C at once, so they are never opened. Inside B there is only one file, and it matches. One file read out of five.</p><h3>Walkthrough 2: a query for October 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*zNnX9fjlNQEJux3asT35dg.png" /></figure><p>Manifest A opens because its label, Oct 1 to 3, includes Oct 2; inside it, per-file partition values skip the other two days. Manifest C opens because Oct 2 has a delete. DuckDB reads both files and drops the deleted rows on the fly.</p><h3>Layer 4 and merge-on-read: why deletes don’t delete</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*_TB6fwTuI6SJMwa8G-Odqw.png" /></figure><p>A position delete file lists a data file and the row positions to ignore. This is how DuckDB’s Iceberg extension handles both DELETE and UPDATE.</p><p>The fix for a pile-up is compaction: rewrite the affected data files without the deleted rows, so readers have nothing left to merge.</p><p>One format note: in Iceberg format version 3, the same positions are stored as a compact binary deletion vector in a Puffin file instead of a Parquet file. The idea is unchanged.</p><h3>Try it yourself in DuckDB</h3><p>DuckDB reads JSON, Avro and Parquet natively, so you can walk every layer with plain SQL. You need the iceberg extension and an Iceberg REST catalog. The quickest local option is the Iceberg project&#39;s REST catalog fixture in Docker:</p><pre>docker run -p 8181:8181 -v /data/lake:/data/lake \<br>  -e CATALOG_WAREHOUSE=/data/lake apache/iceberg-rest-fixture</pre><p>Run the rest in the local DuckDB CLI; the browser shell cannot reach localhost.</p><pre>ATTACH &#39;warehouse&#39; AS lake (<br>  TYPE iceberg, ENDPOINT &#39;http://localhost:8181&#39;, AUTHORIZATION_TYPE &#39;none&#39;<br>);</pre><pre>-- Snapshots: one row per commit<br>SELECT sequence_number, operation FROM iceberg_snapshots(lake.demo.services);</pre><pre>-- Layer 1: where the catalog pointer leads<br>SELECT metadata_location FROM iceberg_load_table_response(lake.demo.services);</pre><pre>-- Layer 1: read the metadata JSON itself<br>SET VARIABLE md = (SELECT metadata_location<br>                   FROM iceberg_load_table_response(lake.demo.services));<br>SELECT &quot;current-snapshot-id&quot;, len(snapshots) FROM read_json(getvariable(&#39;md&#39;));</pre><pre>-- Layer 2: the manifest list of the newest snapshot<br>SET VARIABLE ml = (SELECT manifest_list FROM iceberg_snapshots(lake.demo.services)<br>                   ORDER BY sequence_number DESC LIMIT 1);<br>SELECT manifest_path, content, added_rows_count FROM read_avro(getvariable(&#39;ml&#39;));</pre><pre>-- Layer 3: one row per file, the easy way<br>SELECT manifest_content, file_path, record_count FROM iceberg_metadata(lake.demo.services);</pre><pre>-- Layer 3: the statistics that drive skipping<br>SELECT * FROM iceberg_column_stats(lake.demo.services);<br>SELECT * FROM iceberg_partition_stats(lake.demo.services);</pre><pre>-- Layer 4: what the delete file says to skip<br>SELECT file_path, pos<br>FROM read_parquet(&#39;/data/lake/demo/services/data/*/*-deletes.parquet&#39;,<br>                  hive_partitioning = false);</pre><p>iceberg_metadata does the manifest-list-to-manifest walk for you. Reading the Avro files directly with read_avro is still useful for fields the function does not return, for older snapshots, or for a table that is not in a catalog. On object storage, paths start with s3:// instead of /data/lake; nothing else changes.</p><h3>When looking inside pays off</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HW4jFOoM-LcxI3KpZbu-ZA.png" /></figure><h3>Wrapping up</h3><p>An Iceberg table is a chain of immutable files: catalog pointer, metadata file, manifest list, manifests, then data and delete files. Every query walks that chain from the top, and each layer exists so the reader can throw away work before it touches real data.</p><p>The manifest list skips whole manifests by partition range. The manifests skip individual files by partition value and column bounds. Delete files trade cheap writes for a small merge cost on every read.</p><p>Once you can picture that chain, most Iceberg performance questions turn into a simple one: which layer let too much through?</p><h3>Sources</h3><ul><li>The DuckDB team, <a href="https://duckdb.org/2026/10/13/inside-iceberg-table.html">What Is Inside an Iceberg Table?</a>, DuckDB blog, October 13, 2026. The example table and all figures in this post come from it.</li><li><a href="https://iceberg.apache.org/spec/">Apache Iceberg table spec</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b38f0e085b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Hero: Building an Observability Stack with OpenTelemetry, Prometheus & Grafana]]></title>
            <link>https://medium.com/@amaan2000mohd/from-zero-to-hero-building-an-observability-stack-with-opentelemetry-prometheus-grafana-ff78f41f50a5?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff78f41f50a5</guid>
            <category><![CDATA[otel]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 13:53:55 GMT</pubDate>
            <atom:updated>2026-10-15T13:53:55.383Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Ever wondered what happens behind the scenes when your application becomes slow, your API starts failing, or your CPU usage suddenly spikes?</strong></p><p>You open the logs. Nothing obvious.</p><p>You check the server. It looks healthy.</p><p>But users are still complaining.</p><p>Welcome to one of the biggest challenges in modern software engineering: <strong>understanding what is happening inside your system when something goes wrong.</strong></p><p>In this article, we’ll build an observability pipeline from scratch using three powerful open-source technologies: OpenTelemetry, Prometheus, and Grafana.</p><p>No Kubernetes cluster. No complicated infrastructure. Just the fundamentals, a little code, and a working monitoring stack.</p><p>By the end, you’ll understand how application metrics travel from your code to a database and finally appear on a dashboard.</p><p>Let’s get started!</p><h3>1. First, understand the problem we’re solving</h3><p>Imagine you’re running an e-commerce application.</p><p>Suddenly, customers report that checkout is slow. You need answers to questions like:</p><ul><li>How many requests is the application handling?</li><li>What percentage of requests are failing?</li><li>Is the API response time increasing?</li><li>Which service is becoming a bottleneck?</li></ul><p>Without observability, answering these questions can involve jumping between logs, servers, and multiple monitoring tools.</p><p>What if we could collect application metrics, store them over time, query them, and visualize everything in one place?</p><p>That’s exactly what we’ll build.</p><h3>2. Meet the three heroes</h3><p>Before writing code, let’s understand the responsibility of each component.</p><h3>🧩 OpenTelemetry — The instrumentation layer</h3><p>OpenTelemetry, commonly called OTel, provides a vendor-neutral way to generate and export telemetry from applications.</p><p>It supports three major signals:</p><ul><li><strong>Metrics:</strong> Numerical measurements, such as request counts and latency.</li><li><strong>Traces:</strong> The journey of a request through different services.</li><li><strong>Logs:</strong> Timestamped records of application events.</li></ul><p>For this tutorial, we’ll focus on metrics.</p><p>Think of OpenTelemetry as the instrumentation layer that helps your application tell us what it’s doing.</p><p>Official documentation: <a href="https://opentelemetry.io/docs/">OpenTelemetry</a></p><h3>🗄️ Prometheus — The metrics database</h3><p>Here’s an important distinction: Prometheus isn’t just a monitoring tool. It is also a time-series database.</p><p>It stores measurements alongside timestamps and labels.</p><p>For example:</p><pre>http_requests_total{status=&quot;200&quot;} 1500<br>http_requests_total{status=&quot;500&quot;} 25</pre><p>These metrics can tell us how many successful and failed requests our application has recorded.</p><p>Prometheus also provides PromQL, a query language for analyzing metrics.</p><p>Official documentation: <a href="https://prometheus.io/docs/introduction/overview/">Prometheus</a></p><h3>📊 Grafana — The visualization layer</h3><p>Raw metrics are useful, but dashboards make them easier to understand.</p><p>Grafana connects to Prometheus, queries its data, and displays the results through graphs, tables, gauges, and other visualizations.</p><p>Instead of manually checking numbers, you can create a dashboard showing:</p><ul><li>Request rate</li><li>Error percentage</li><li>Response latency</li><li>CPU and memory utilization</li></ul><p>Official documentation: <a href="https://grafana.com/docs/">Grafana</a></p><h3>3. How do these components work together?</h3><p>For our implementation, we’ll use an OpenTelemetry Collector between the application and Prometheus.</p><p>Here’s the complete architecture:</p><pre>┌───────────────────────────┐<br>│      Python Application   │<br>│                           │<br>│  OpenTelemetry SDK        │<br>│  Generates Metrics        │<br>└─────────────┬─────────────┘<br>              │<br>              │ OTLP / HTTP<br>              ▼<br>┌───────────────────────────┐<br>│ OpenTelemetry Collector   │<br>│                           │<br>│ Receives &amp; Exposes Metrics│<br>└─────────────┬─────────────┘<br>              │<br>              │ Prometheus Scrape<br>              ▼<br>┌───────────────────────────┐<br>│        Prometheus         │<br>│                           │<br>│ Stores Time-Series Data   │<br>│ Executes PromQL Queries   │<br>└─────────────┬─────────────┘<br>              │<br>              │ PromQL<br>              ▼<br>┌───────────────────────────┐<br>│          Grafana          │<br>│                           │<br>│ Dashboards &amp; Visualization│<br>└───────────────────────────┘</pre><p>The flow is straightforward:</p><ol><li>The application generates metrics using OpenTelemetry.</li><li>The application sends those metrics to the Collector through OTLP.</li><li>The Collector exposes a Prometheus-compatible metrics endpoint.</li><li>Prometheus periodically scrapes that endpoint and stores the measurements.</li><li>Grafana queries Prometheus and displays the data.</li></ol><p><strong>Remember:</strong> OpenTelemetry generates and transports telemetry, Prometheus stores and queries metrics, and Grafana visualizes them.</p><p>The Collector is a useful component in this architecture, although it isn’t mandatory for every OpenTelemetry-to-Prometheus setup.</p><h3>4. Let’s build it!</h3><p>We’ll create a small Python application that generates simulated request metrics.</p><p>You’ll need Docker and Docker Compose installed.</p><p>Create this project structure:</p><pre>observability-demo/<br>├── app/<br>│   ├── Dockerfile<br>│   ├── requirements.txt<br>│   └── app.py<br>├── collector-config.yaml<br>├── prometheus.yml<br>└── docker-compose.yml</pre><h3>Step 1: Install the OpenTelemetry dependencies</h3><p>Inside app/requirements.txt, add:</p><pre>opentelemetry-api<br>opentelemetry-sdk<br>opentelemetry-exporter-otlp-proto-http</pre><p>These packages provide the OpenTelemetry API, SDK, and OTLP HTTP exporter.</p><h3>Step 2: Create the application</h3><p>Create app/app.py:</p><pre>import random<br>import time</pre><pre>from opentelemetry import metrics<br>from opentelemetry.sdk.metrics import MeterProvider<br>from opentelemetry.sdk.metrics.export import (<br>    PeriodicExportingMetricReader,<br>)<br>from opentelemetry.exporter.otlp.proto.http.metric_exporter import (<br>    OTLPMetricExporter,<br>)<br>from opentelemetry.sdk.resources import Resource</pre><pre>resource = Resource.create({<br>    &quot;service.name&quot;: &quot;checkout-service&quot;<br>})</pre><pre>exporter = OTLPMetricExporter(<br>    endpoint=&quot;http://otel-collector:4318/v1/metrics&quot;<br>)</pre><pre>reader = PeriodicExportingMetricReader(<br>    exporter,<br>    export_interval_millis=5000,<br>)</pre><pre>provider = MeterProvider(<br>    resource=resource,<br>    metric_readers=[reader],<br>)</pre><pre>metrics.set_meter_provider(provider)</pre><pre>meter = metrics.get_meter(&quot;checkout-service&quot;)</pre><pre>requests = meter.create_counter(<br>    &quot;checkout.requests&quot;,<br>    description=&quot;Total simulated checkout requests&quot;,<br>)</pre><pre>latency = meter.create_histogram(<br>    &quot;checkout.request.duration&quot;,<br>    unit=&quot;s&quot;,<br>    description=&quot;Checkout request duration&quot;,<br>)</pre><pre>try:<br>    while True:<br>        status = random.choice(<br>            [&quot;success&quot;, &quot;success&quot;, &quot;success&quot;, &quot;error&quot;]<br>        )</pre><pre>        duration = random.uniform(0.05, 1.5)</pre><pre>        requests.add(1, {&quot;status&quot;: status})<br>        latency.record(duration, {&quot;status&quot;: status})</pre><pre>        print(<br>            f&quot;status={status}, &quot;<br>            f&quot;duration={duration:.3f}s&quot;<br>        )</pre><pre>        time.sleep(1)</pre><pre>except KeyboardInterrupt:<br>    pass</pre><pre>finally:<br>    provider.shutdown()</pre><p>What’s happening here?</p><p>We’re creating two metrics:</p><ul><li>A <strong>counter</strong> that tracks the number of checkout requests.</li><li>A <strong>histogram</strong> that records request durations so we can analyze latency distributions.</li></ul><p>Every second, the application generates a simulated request and records its status and duration.</p><p>The service.name resource attribute identifies the service producing the telemetry.</p><p>Notice that we’re not writing code to store anything in a database. OpenTelemetry handles instrumentation and exporting; the metrics backend will handle storage.</p><h3>Step 3: Create the Dockerfile</h3><p>Create app/Dockerfile:</p><pre>FROM python:3.12-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY app.py .<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>This builds a lightweight container for our Python application.</p><h3>Step 4: Configure the OpenTelemetry Collector</h3><p>Create collector-config.yaml:</p><pre>receivers:<br>  otlp:<br>    protocols:<br>      http:<br>        endpoint: 0.0.0.0:4318<br>exporters:<br>  prometheus:<br>    endpoint: 0.0.0.0:9464<br>service:<br>  pipelines:<br>    metrics:<br>      receivers: [otlp]<br>      exporters: [prometheus]</pre><p>Let’s decode this configuration.</p><ul><li><strong>Receiver:</strong> Accepts metrics from the application over OTLP/HTTP.</li><li><strong>Exporter:</strong> Exposes the received metrics in Prometheus format on port 9464.</li><li><strong>Pipeline:</strong> Connects the receiver and exporter.</li></ul><p>Our Collector now acts as the bridge between OpenTelemetry and Prometheus.</p><h3>Step 5: Configure Prometheus</h3><p>Create prometheus.yml:</p><pre>global:<br>  scrape_interval: 5s<br>scrape_configs:<br>  - job_name: &quot;otel-collector&quot;<br>    static_configs:<br>      - targets: [&quot;otel-collector:9464&quot;]</pre><p>This tells Prometheus to scrape the Collector every five seconds.</p><p>Notice that we’re using otel-collector:9464 rather than localhost:9464.</p><p>Why?</p><p>Because the services run inside Docker Compose. They can communicate using their service names over the shared Docker network.</p><h3>Step 6: Bring everything together</h3><p>Create docker-compose.yml:</p><pre>services:<br>  app:<br>    build: ./app<br>    depends_on:<br>      - otel-collector<br>otel-collector:<br>    image: otel/opentelemetry-collector-contrib:latest<br>    command:<br>      - &quot;--config=/etc/otelcol-contrib/config.yaml&quot;<br>    volumes:<br>      - ./collector-config.yaml:/etc/otelcol-contrib/config.yaml:ro<br>    ports:<br>      - &quot;4318:4318&quot;<br>      - &quot;9464:9464&quot;<br>  prometheus:<br>    image: prom/prometheus:latest<br>    command:<br>      - &quot;--config.file=/etc/prometheus/prometheus.yml&quot;<br>    volumes:<br>      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro<br>    ports:<br>      - &quot;9090:9090&quot;<br>  grafana:<br>    image: grafana/grafana:latest<br>    ports:<br>      - &quot;3000:3000&quot;</pre><p>For a repeatable setup, pin container images to tested versions rather than using latest.</p><p>Start the stack:</p><pre>docker compose up --build -d</pre><p>Check the application and Collector logs:</p><pre>docker compose logs -f app otel-collector</pre><p>Give the services a few seconds to initialize.</p><p>One practical note: depends_on controls startup order but doesn&#39;t guarantee readiness. If the Collector isn&#39;t ready when the application starts, check the logs and allow the exporter to retry.</p><p>Congratulations! Your metrics pipeline is running. 🎉</p><h3>5. Verify your metrics in Prometheus</h3><p>Open Prometheus in your browser:</p><p><a href="http://localhost:9090/">http://localhost:9090</a></p><p>Navigate to <strong>Status → Targets</strong> and verify that the otel-collector target is up.</p><p>Next, search for your metric names in the query interface.</p><p>OpenTelemetry metric names may be translated into Prometheus-compatible names. For our example, the counter will typically appear as checkout_requests_total, while the histogram may appear as checkout_request_duration_seconds_bucket.</p><p>Use the actual names displayed by your Prometheus instance if they differ.</p><h3>Query 1: How many requests are we processing?</h3><pre>sum(rate(checkout_requests_total[1m]))</pre><p>This calculates the estimated request rate per second over the last minute.</p><h3>Query 2: How many successful and failed requests are occurring?</h3><pre>sum by (status) (<br>  rate(checkout_requests_total[1m])<br>)</pre><p>This separates the request rate by the status label.</p><h3>Query 3: What’s our error percentage?</h3><pre>100 *<br>sum(rate(checkout_requests_total{status=&quot;error&quot;}[5m]))<br>/<br>sum(rate(checkout_requests_total[5m]))</pre><p>This estimates the percentage of requests labeled as errors over the last five minutes.</p><h3>Query 4: What’s our 95th-percentile latency?</h3><pre>histogram_quantile(<br>  0.95,<br>  sum by (le) (<br>    rate(checkout_request_duration_seconds_bucket[5m])<br>  )<br>)</pre><p>This estimates the 95th-percentile duration from histogram buckets, assuming the corresponding bucket series are available.</p><p>Why does this matter?</p><p>An average response time can look healthy even when a portion of users experiences very slow requests. Percentiles help reveal that tail latency.</p><p><strong>This is where metrics become useful: you’re no longer guessing what’s happening in your application. You’re querying evidence.</strong></p><h3>6. Turn your metrics into dashboards with Grafana</h3><p>Open Grafana:</p><p><a href="http://localhost:3000/">http://localhost:3000</a></p><p>For a fresh local installation, the initial credentials are typically admin / admin; follow the password-change prompt if shown.</p><p>Now configure the Prometheus data source:</p><ol><li>Navigate to <strong>Connections → Data sources</strong>.</li><li>Select <strong>Add new data source</strong>.</li><li>Choose <strong>Prometheus</strong>.</li><li>Set the URL to <a href="http://prometheus:9090.">http://prometheus:9090.</a></li><li>Select <strong>Save &amp; test</strong>.</li></ol><p>Why not use localhost:9090?</p><p>Inside the Grafana container, localhost refers to Grafana itself. The hostname prometheus resolves to the Prometheus container on the Docker network.</p><p>Next, create a dashboard and add panels for:</p><ul><li><strong>Request rate:</strong> Requests processed per second.</li><li><strong>Error rate:</strong> Percentage of failed requests.</li><li><strong>Request latency:</strong> Estimated p95 duration.</li><li><strong>Request status:</strong> Success versus error rates.</li></ul><p>Set the dashboard’s time range to the last 15 minutes and enable automatic refresh.</p><p>You now have a live dashboard that turns application telemetry into something you can understand at a glance.</p><h3>7. What have we actually built?</h3><p>Let’s step back and look at what each component contributes.</p><p>ComponentResponsibilityOpenTelemetry SDKGenerates application metricsOpenTelemetry CollectorReceives and exposes metricsPrometheusScrapes, stores, and queries metricsGrafanaVisualizes the results</p><p>The most important distinction is that <strong>Prometheus is the metrics database, while Grafana is the visualization layer</strong>.</p><p>Grafana doesn’t need to store your application’s metrics itself. It queries Prometheus whenever a dashboard needs data.</p><p>OpenTelemetry also isn’t a database. It provides the instrumentation and telemetry pipeline that makes the data available to your observability backend.</p><p>Once these responsibilities are clear, the architecture becomes much easier to reason about.</p><h3>8. From a demo to production observability</h3><p>Our local setup is a learning environment, not a production-ready deployment.</p><p>Before using a similar architecture in production, consider:</p><ul><li>Pinning container versions and managing upgrades.</li><li>Configuring persistent storage and retention for Prometheus.</li><li>Securing exposed endpoints and credentials.</li><li>Adding Collector batching, memory limits, retries, and monitoring.</li><li>Designing metrics and labels carefully to avoid excessive cardinality.</li><li>Creating meaningful alerts rather than relying only on dashboards.</li><li>Adding traces and logs when you need deeper troubleshooting.</li></ul><p>Also remember that the Collector is optional in some architectures. Prometheus supports direct OTLP metric ingestion when its OTLP receiver is explicitly enabled. The Collector-based approach shown here is useful when you want a flexible, centralized telemetry pipeline.</p><h3>9. Your next challenge 🎯</h3><p>Now that you’ve built the foundation, try extending it:</p><ol><li>Replace the simulated requests with a real FastAPI endpoint.</li><li>Track actual HTTP request counts and durations.</li><li>Add a dashboard that shows p95 latency and error percentage.</li><li>Trigger an alert when the error rate exceeds a threshold.</li><li>Add distributed tracing and connect slow requests to their underlying operations.</li></ol><p>These exercises will help you move from understanding the architecture to applying observability in a real application.</p><h3>Final thoughts</h3><p>Observability doesn’t have to start with a massive monitoring platform or a complex Kubernetes deployment.</p><p>It can start with a single application, a few well-designed metrics, and a dashboard that answers meaningful questions.</p><p>OpenTelemetry gives your application a standardized way to emit telemetry. Prometheus stores and queries the metrics. Grafana turns those metrics into insights you can act on.</p><p>Together, they provide a powerful foundation for understanding modern applications.</p><p><strong>The real goal isn’t to build more dashboards. It’s to reduce the time between something going wrong and understanding why.</strong></p><p>Start small. Follow the data. Ask better questions.</p><p>That’s how you go from zero to hero in observability. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff78f41f50a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis GEO: The Geospatial Database You’re Already Running]]></title>
            <link>https://medium.com/@amaan2000mohd/redis-geo-the-geospatial-database-youre-already-running-737d5d599fb6?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/737d5d599fb6</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 11:24:14 GMT</pubDate>
            <atom:updated>2026-10-07T11:24:14.081Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Sub-millisecond “who’s nearby” queries over a million moving points. No PostGIS, no new service, no ETL. A deep dive on how Redis folds two dimensions into one — and exactly where that trick runs out.</em></p><h3>The “Find Nearby Drivers” Ticket That Started It</h3><p>The story is roughly the same everywhere.</p><p>You are three sprints into a product that works fine. Then a ticket lands: <em>show the user the five nearest drivers.</em> Or the nearest stores, or listings within 10 km, or who else is at this event. Simple feature. Half a day, you think.</p><p>Then you open the design doc and it has grown teeth. You need a spatial index. Your Postgres does not have PostGIS enabled. Enabling PostGIS means a migration, a review, and a conversation with whoever owns the database. Someone suggests Elasticsearch. Someone else suggests a managed geo API with a per-call price. The half-day feature is now a two-week infrastructure project.</p><p>Then somebody on the team says: <em>we already run Redis, you know.</em></p><pre>&gt; GEOADD drivers 72.8777 19.0760 &quot;driver:4812&quot;<br>(integer) 1<br>&gt; GEOSEARCH drivers FROMLONLAT 72.878 19.076 BYRADIUS 3 km ASC WITHDIST<br>1) 1) &quot;driver:4812&quot;<br>   2) &quot;0.0612&quot;</pre><p>That is the whole feature. Two commands. No new service, no migration, no bill. The query came back in well under a millisecond, and it will still come back in well under a millisecond when there are a million drivers in that key.</p><p>Redis has shipped geospatial commands since version 3.2, and a surprising number of engineers have never touched them — partly because “Redis” and “geospatial” do not sit together in most people’s mental model. They should. The feature is small, fast, and built on something you already understand.</p><p>This post is a tour of what Redis GEO actually is, the one idea that makes it work, the five commands you need, the four patterns where it wins, and the honest limitations. By the end, you will know whether you can close that ticket this afternoon or whether you genuinely need the spatial database.</p><h3>What Redis GEO Actually Is</h3><p>Here is the surprise: <strong>there is no geo data type in Redis.</strong></p><p>A geo key is an ordinary sorted set. Not a sorted set with extra features — the same sorted set you have used for leaderboards and rate limiters. You can prove it in three lines:</p><pre>&gt; GEOADD cities 72.8777 19.0760 &quot;Mumbai&quot;<br>(integer) 1<br>&gt; TYPE cities<br>zset<br>&gt; ZSCORE cities Mumbai<br>&quot;3675435431449536&quot;</pre><p>The GEO* commands are a thin layer that computes clever scores and interprets them back. That is the entire feature. Everything good about Redis GEO, and everything frustrating about it, follows from this one fact.</p><p>The good: it inherits replication, persistence, clustering, atomicity, and the whole sorted-set command set for free. The frustrating: anything a sorted set cannot do, Redis GEO cannot do either — which we will get to honestly, later.</p><h3>How It Actually Works (The One Idea Worth Understanding)</h3><p>That strange score is where the magic lives. Understanding it takes about two minutes and makes every behaviour of these commands predictable.</p><h3>The problem: two dimensions, one index</h3><p>Sorting is a one-dimensional idea. You can sort numbers on a line. A location is two numbers — longitude and latitude — and there is no obvious way to sort a map.</p><p>Sort by longitude alone, and two points on the same meridian are “adjacent” even if one is in Mumbai and one is in Antarctica. Sort by latitude alone, same problem sideways. Neither ordering says anything useful about nearness.</p><h3>The trick: interleave the bits</h3><p>Redis takes the longitude and squeezes it onto a 26-bit integer, does the same for the latitude, then <strong>weaves the two together</strong> — one bit of longitude, one bit of latitude, one bit of longitude, and so on — into a single 52-bit number called a geohash.</p><pre>longitude bits:  1 0 1 1 0 ...<br>latitude bits:    0 1 1 0 1 ...<br>interleaved:     10 01 11 10 01 ...   -&gt;  one 52-bit number</pre><p>Why 52? Because a 64-bit float can hold a 52-bit integer exactly, with no rounding. So the geohash fits perfectly into a sorted set’s score, which is a float. No precision is lost, no second structure is needed.</p><p>The property that makes this work is <strong>locality</strong>. Because the bits alternate, two points physically close to each other share a long prefix of their geohash, which puts them close together in the sorted set’s ordering. Think of it as drawing one long squiggly line that visits every part of the map without big jumps, then numbering points along that line.</p><p>So a two-dimensional search problem has quietly become a one-dimensional range scan — and range scans on sorted sets are something Redis does extremely well.</p><h3>What a radius query actually does</h3><p>When you ask for everything within 3 km of a point, Redis:</p><ol><li>Works out which geohash cells cover that circle (usually nine neighbouring cells).</li><li>Runs a ZRANGEBYSCORE over each cell&#39;s score range — cheap, because the sorted set is already in that order.</li><li>Computes the true distance for every candidate it found.</li><li>Throws away the ones that were in the box but outside the circle.</li></ol><p>Steps 3 and 4 are why a radius query costs more than a plain range scan, and why a huge radius over a dense city gets slow. You are paying for candidates, not for results.</p><h3>Two things to take away</h3><p><strong>Precision is not your problem.</strong> The 52-bit encoding resolves to roughly half a metre. Consumer GPS is far less accurate than that, so the encoding will never be the weak link in your accuracy.</p><p><strong>Every sorted set command still works.</strong> ZREM, ZCARD, ZSCAN, ZINTERSTORE — all of them operate on a geo key. This is not a curiosity; it is how you do deletions and filtering, since the GEO* family does not cover them.</p><h3>Five Commands, and That’s the Entire API</h3><p>There is no large surface area to learn here. Five commands cover everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGuHf2h08-fOEdTZuRiGMw.png" /></figure><p>GEOADD: longitude first (yes, really)</p><pre>GEOADD drivers 72.8777 19.0760 &quot;driver:4812&quot;<br>            ^lon      ^lat     ^member</pre><p><strong>Longitude comes first.</strong> Every map UI you have ever used writes latitude first, so this catches almost everyone at least once. Redis follows the GeoJSON convention. Get it backwards and you get no error at all — just results from the wrong part of the planet.</p><p>The useful flags:</p><pre>GEOADD drivers NX 72.83 18.92 &quot;driver:5501&quot;       # only add if new, never move<br>GEOADD drivers XX 72.84 18.93 &quot;driver:5501&quot;       # only move if already there<br>GEOADD drivers CH 72.84 18.93 &quot;driver:5501&quot;       # return count of changes, not adds</pre><p>The important behaviour: <strong>GEOADD is an upsert.</strong> Sending a new position for an existing member rewrites it in place. You never need to delete first, which is exactly what makes a high-frequency location feed cheap.</p><h3>GEOSEARCH: the one you’ll actually use</h3><p>GEOSEARCH replaced the older GEORADIUS and GEORADIUSBYMEMBER, which were <a href="https://redis.io/docs/latest/commands/georadius/">deprecated in Redis 6.2</a>. If a tutorial you find online uses GEORADIUS, it is pre-6.2. The old commands still work, but they carry a STORE option, which means Redis flags them as <em>write</em> commands — so replicas will redirect or reject them even on a read-only connection. Use the new ones.</p><pre># everything within 3 km of a point, nearest first, with distances<br>GEOSEARCH drivers FROMLONLAT 72.8777 19.0760 BYRADIUS 3 km ASC WITHDIST WITHCOORD</pre><pre># a rectangle instead of a circle, centred on a member already in the set<br>GEOSEARCH drivers FROMMEMBER &quot;driver:4812&quot; BYBOX 4 2 km ASC COUNT 10</pre><p>It reads like a sentence once you see the four slots:</p><ul><li><strong>Where from:</strong> FROMLONLAT lon lat or FROMMEMBER name</li><li><strong>What shape:</strong> BYRADIUS 3 km or BYBOX 4 2 km</li><li><strong>How to order and cap:</strong> ASC / DESC, COUNT n</li><li><strong>What extras you want back:</strong> WITHDIST, WITHCOORD, WITHHASH</li></ul><h3>The flag that quietly doubles your speed</h3><p>COUNT n ANY deserves its own section, because almost nobody knows about it and it is the single biggest performance lever in the whole API.</p><p>Without ANY, Redis finds <strong>every</strong> match in the area, sorts them all by distance, then hands you the first n. With ANY, it stops the moment it has n results and returns them unsorted.</p><pre>GEOSEARCH restaurants FROMLONLAT 72.87 19.07 BYRADIUS 2 km COUNT 10 ANY</pre><p>In a dense neighbourhood with 4,000 restaurants inside a 2 km circle, the first version does 4,000 distance calculations and a sort to give you ten. The second does roughly ten. For “show me some places nearby”, no user has ever noticed that these were not the ten closest. Use ANY whenever &quot;nearby&quot; is good enough and &quot;nearest&quot; is not required.</p><h3>Where Redis GEO Wins: Four Real Patterns</h3><h3>1. Live tracking and dispatch</h3><p>The flagship use case. Drivers, couriers, field technicians — things that move constantly and need to be matched to a request <em>now</em>.</p><pre>import time<br>import redis</pre><pre>r = redis.Redis(decode_responses=True)<br>KEY = &quot;drivers:available&quot;</pre><pre>def update_position(driver_id: str, lon: float, lat: float) -&gt; None:<br>    &quot;&quot;&quot;Called on every GPS ping. GEOADD upserts, so no read first.&quot;&quot;&quot;<br>    pipe = r.pipeline()<br>    pipe.geoadd(KEY, (lon, lat, driver_id))<br>    pipe.hset(f&quot;driver:{driver_id}&quot;, &quot;seen&quot;, int(time.time()))<br>    pipe.execute()</pre><pre>def go_offline(driver_id: str) -&gt; None:<br>    &quot;&quot;&quot;There is no GEOREM. It&#39;s a sorted set, so ZREM is the delete.&quot;&quot;&quot;<br>    r.zrem(KEY, driver_id)</pre><pre>def nearest_drivers(lon: float, lat: float, km: float = 3, limit: int = 10):<br>    return r.geosearch(<br>        KEY,<br>        longitude=lon, latitude=lat,<br>        radius=km, unit=&quot;km&quot;,<br>        sort=&quot;ASC&quot;, count=limit,<br>        withdist=True, withcoord=True,<br>    )</pre><pre>&gt;&gt;&gt; update_position(&quot;driver:4812&quot;, 72.8777, 19.0760)<br>&gt;&gt;&gt; update_position(&quot;driver:5501&quot;, 72.8831, 19.0812)<br>&gt;&gt;&gt; nearest_drivers(72.8780, 19.0765)<br>[[&#39;driver:4812&#39;, 0.0612, (72.87769, 19.07600)],<br> [&#39;driver:5501&#39;, 0.7284, (72.88310, 19.08120)]]</pre><p>Three design choices in there are worth copying:</p><ul><li><strong>One write per ping.</strong> No read-modify-write, no race between two pings from the same device. Just GEOADD.</li><li><strong>Keep the geo key skinny.</strong> Only the id goes in the sorted set. Vehicle type, rating, fare, last-seen — all in a separate hash. The index stays small, and updating a rating never touches it.</li><li><strong>Start tight, retry wider.</strong> If 3 km finds nothing at 4 a.m., try 8 km. Two cheap queries beat one expensive one, and the common case stays fast.</li></ul><h3>2. Store locators and “what’s near me”</h3><p>The static cousin: points that barely ever move. Branches, pickup lockers, charging stations, ATMs.</p><pre>GEOADD stores 72.8311 18.9220 &quot;store:bandra&quot;<br>GEOADD stores 72.8777 19.0760 &quot;store:andheri&quot;<br>GEOSEARCH stores FROMLONLAT 72.85 19.00 BYRADIUS 10 km ASC WITHDIST COUNT 5</pre><p>Because the data rarely changes, this is the easiest thing in the world to treat as a cache. Your real store list lives in Postgres; a cron job rebuilds the Redis key from it every night. Lose the key and you lose nothing — rebuild and carry on.</p><h3>3. Filtered proximity search</h3><p>“Nearest drivers <strong>that accept card payment</strong>.” Redis GEO cannot filter on attributes — but GEOSEARCHSTORE writes a real sorted set, so you can hand the result to the rest of the sorted-set toolbox.</p><pre># 1. narrow by geography, into a temp key<br>GEOSEARCHSTORE tmp:req:9f31 drivers:available \<br>  FROMLONLAT 72.878 19.076 BYRADIUS 3 km ASC COUNT 50</pre><pre># 2. intersect with a set you maintain separately<br>ZINTERSTORE tmp:req:9f31:card 2 tmp:req:9f31 drivers:accepts_card WEIGHTS 1 0</pre><pre># 3. always clean up after yourself<br>EXPIRE tmp:req:9f31 30<br>EXPIRE tmp:req:9f31:card 30</pre><p>WEIGHTS 1 0 is the detail that makes this work: it keeps the distance ordering from the geo search and ignores the scores in the filter set, so your results stay sorted by how close they are.</p><h3>4. Geofencing and proximity alerts</h3><p>You want to know when someone enters an area — a delivery zone, a store’s catchment, a restricted site. Run the search from the fence’s centre on each position update.</p><pre>def check_fences(user_id: str, lon: float, lat: float):<br>    r.geoadd(&quot;users:live&quot;, (lon, lat, user_id))<br>    for fence in ACTIVE_FENCES:<br>        inside = r.geosearch(<br>            &quot;users:live&quot;,<br>            longitude=fence.lon, latitude=fence.lat,<br>            radius=fence.radius_m, unit=&quot;m&quot;,<br>        )<br>        was_inside = r.sismember(f&quot;fence:{fence.id}:inside&quot;, user_id)<br>        if user_id in inside and not was_inside:<br>            r.sadd(f&quot;fence:{fence.id}:inside&quot;, user_id)<br>            emit(&quot;fence_entered&quot;, user_id, fence.id)<br>        elif user_id not in inside and was_inside:<br>            r.srem(f&quot;fence:{fence.id}:inside&quot;, user_id)<br>            emit(&quot;fence_exited&quot;, user_id, fence.id)</pre><p>The set membership is doing the work of remembering state, so you get entry and exit events rather than a stream of “still inside” noise. This stays cheap up to a few hundred fences; past that, you want a proper geofencing engine.</p><h3>What It Costs</h3><p>Writes are the boring part. GEOADD is O(log N), the same as ZADD. A single Redis core handles hundreds of thousands of position updates per second without breaking a sweat. You will run out of network before you run out of Redis.</p><p>Reads are where judgement is required. GEOSEARCH is O(N + log M) — and that <strong>N is the number of candidates inside the bounding box</strong>, not the number of results you get back.</p><p>That distinction is the whole performance story. A 1 km radius in rural Rajasthan and a 1 km radius in south Mumbai have identical big-O and wildly different wall-clock times, because one box contains four candidates and the other contains forty thousand. The query that pages you at 3 a.m. is always a wide radius over a dense key.</p><p>Three levers, in order of how much they help:</p><ol><li><strong>Use </strong><strong>COUNT n ANY</strong> when any n nearby matches will do. Biggest single win in dense areas, because Redis gets to stop early instead of scanning and sorting the whole box.</li><li><strong>Start with a tight radius and widen on an empty result.</strong> Most lookups resolve on the first, cheap attempt.</li><li><strong>Split the key by region</strong> once one key gets large — drivers:mumbai, drivers:delhi. You trade a routing decision in your code for a far smaller N per query.</li></ol><p><strong>Memory</strong> is modest. A geo member is just a sorted set entry: the member string, the score, and skiplist overhead — roughly a hundred bytes each once the set outgrows its compact encoding. A million drivers is tens of megabytes, not gigabytes. Shortening members (d:4812 rather than a full UUID) is a real saving at scale.</p><p><strong>One cluster gotcha.</strong> Geo commands work on a single key, so Redis Cluster shards your index by key name, not by geography. Regional keys landing on different nodes is fine — but GEOSEARCHSTORE and ZINTERSTORE need their source and destination in the same hash slot. Use hash tags: {mumbai}:drivers and {mumbai}:tmp:req:9f31.</p><h3>Redis GEO vs The Alternatives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*br6jQ9f2jBz2JMBBfHSWpA.png" /></figure><p>The short version: <strong>Redis GEO is the default for points that move fast and queries that are circles.</strong> PostGIS owns anything where geography is the data model. Elasticsearch owns geo-plus-relevance. A routing engine owns the question of how long it actually takes to get there.</p><p>And they are not exclusive. The pattern that works best in practice is Postgres or PostGIS as the durable store, with Redis GEO as a hot index in front of it that you can drop and rebuild at any time.</p><h3>Where Redis GEO Doesn’t Shine (Be Honest)</h3><p>It is a thin layer over a sorted set, and the limits of that layer are real. The honest list:</p><h3>1. Longitude comes first</h3><p>Saying it a second time because it is the single most common Redis GEO bug. Wrong order gives you confident, plausible-looking results from the wrong hemisphere, with no error raised. Write a test that asserts a known landmark’s distance and you will never debug this at midnight.</p><h3>2. There is no GEOREM</h3><p>Deletion is ZREM. Nothing warns you about this. Forget it, and offline drivers stay in your index forever — riders get matched to a car that went home three weeks ago. Keep a seen timestamp and sweep the stale entries on a timer:</p><pre>ZADD drivers:lastseen 1759800000 &quot;driver:4812&quot;<br># every minute: anything not seen in 5 minutes gets dropped<br>ZREMRANGEBYSCORE drivers:lastseen -inf &lt;now-300&gt;</pre><h3>3. TTLs apply to the key, not the member</h3><p>You cannot expire one driver out of the index. Redis has no per-member expiry inside a sorted set, so expiry is your job — either the sweep above, or one key per short time bucket that you let expire wholesale.</p><h3>4. Circles and rectangles only</h3><p>No polygons. No “inside this delivery zone”, no “within this postcode boundary”. If your shapes are real shapes, Redis GEO cannot express the query. The workaround — over-fetch with a generous radius and do point-in-polygon in application code — works, but if you are doing it on every request, you have outgrown this tool.</p><h3>5. Distances are straight lines, not roads</h3><p>GEODIST Returns great-circle distance. A driver 400 m away across a river with no bridge is not 400 m away. Redis GEO is a <strong>candidate generator</strong>; a routing engine makes the real decision. Pull twenty nearby drivers with Redis in a millisecond, then ask OSRM for drive times on those twenty.</p><h3>6. No pagination</h3><p>COUNT Caps a result; it does not offset one. There is no cursor into a radius search. If you need page two, GEOSEARCHSTORE the result into a key and page <em>that</em> with ZRANGE.</p><h3>7. The poles don’t exist</h3><p>Valid latitudes stop at roughly ±85.05 degrees, a consequence of the Web Mercator projection the encoding is based on. Unlikely to matter — unless you are writing software for Antarctic research stations, in which case, sorry.</p><h3>8. It’s a cache, so treat it like one</h3><p>Redis persistence is good, but most teams run Redis in a configuration where losing a little data on failover is acceptable. Your geo index should be rebuildable from a durable source. If the only copy of where your couriers are lives in a Redis key, you have made a bet you probably did not intend to make.</p><h3>When to Reach for Redis GEO</h3><p><strong>Use it when:</strong></p><ul><li>You already run Redis and a “near me” feature just landed on your board</li><li>Your points move constantly — drivers, couriers, users, devices</li><li>The query is a circle or a rectangle, not a real shape</li><li>You need an answer in under a millisecond</li><li>The index can be rebuilt from a durable source if you lose it</li><li>You want a candidate list to hand to a routing engine</li><li>You are prototyping, and you would rather find out from real traffic whether you need more</li></ul><p><strong>Don’t use it when:</strong></p><ul><li>Geography is your system of record — use PostGIS</li><li>You need polygons, intersections, or joins against geometry — use PostGIS</li><li>The geo filter rides along with text relevance (“vegetarian thali, open now, within 2 km, best rated”) — use Elasticsearch</li><li>The number that matters is drive time, not straight-line distance — use OSRM or Valhalla</li><li>You need per-member expiry, pagination, or attribute filters without writing extra machinery</li></ul><h3>A Closing Thought</h3><p>What I like about Redis GEO is not that it is fast. Plenty of things are fast.</p><p>It is that somebody looked at a hard two-dimensional problem and found a way to make it a one-dimensional problem that an existing data structure already solved. No new storage engine, no new index type — just a better way of numbering the points. The whole feature is a few hundred lines of C sitting on top of a sorted set.</p><p>That is also why the limits are so sharply defined. Everything a sorted set can do, Redis GEO does beautifully. Everything it cannot do is simply absent — no half-working polygon support, no slow-path fallback. The tool is honest about its own shape, which is rarer than it should be.</p><p>So before the two-week infrastructure project, spend ten minutes:</p><pre>GEOADD places 72.8777 19.0760 &quot;first&quot;<br>GEOSEARCH places FROMLONLAT 72.878 19.076 BYRADIUS 1 km ASC WITHDIST</pre><p>You might already be done.</p><p><em>If you have shipped Redis GEO in production — or tried it and moved to PostGIS — I’d love to hear where the line was for you, and what surprised you most.</em></p><p><em>Further reading: the </em><a href="https://redis.io/docs/latest/commands/georadius/"><em>Redis geospatial command reference</em></a><em>. If you want to see the bit-interleaving for yourself, </em><em>geo.c and </em><em>geohash.c in the Redis source are unusually readable.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737d5d599fb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sonnet 5 Is Live. The Real Story Isn’t the Benchmarks — It’s the Price.]]></title>
            <link>https://medium.com/@amaan2000mohd/80-4-vs-74-6-the-sonnet-5-number-nobodys-talking-about-29e2acb6478e?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/29e2acb6478e</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[antropic]]></category>
            <category><![CDATA[sonnet]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 05:24:14 GMT</pubDate>
            <atom:updated>2026-07-02T13:28:38.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Anthropic launched Claude Sonnet 5 on June 30. Everyone’s rushing to compare benchmark scores across mismatched harnesses. The number that actually matters is on the pricing page.</em></p><p><strong>$2 per million input tokens. $10 per million output.</strong></p><p>That’s Claude Sonnet 5’s introductory price through August 31, 2026. Opus 4.8 sits at $5/$25.</p><p>Same 1M context window. Same API. Same tokenizer generation. And, per Anthropic’s own launch materials, Sonnet 5 lands close enough to Opus 4.8 on the benchmarks that matter for agentic work that the two now cover <strong>a single cost-performance curve</strong> instead of two separate tiers.</p><p>That last part is the actual story. Not “the mid-tier beat the flagship” — that framing is popping up in third-party writeups and doesn’t survive contact with the primary leaderboards. The actual story is quieter: the price of near-frontier performance just dropped by more than half. That changes the model-selection question for anyone shipping agents in production.</p><p>Here’s my read after 48 hours.</p><h3>What actually shipped (sourced from Anthropic’s launch page)</h3><p>The confirmed facts from <a href="https://www.anthropic.com/news/claude-sonnet-5">anthropic.com/news/claude-sonnet-5</a>:</p><ul><li>Released June 30, 2026</li><li>Default model for Free and Pro plans on claude.ai</li><li>Available on Max, Team, Enterprise, Claude Code, and the Claude Platform</li><li><strong>Introductory pricing</strong> through August 31: $2 input / $10 output per million tokens</li><li><strong>Standard pricing</strong> from September: $3/$15</li><li><strong>Opus 4.8</strong> remains at $5/$25 per million tokens</li><li><strong>1M-token context window</strong></li><li><strong>New: selectable reasoning effort levels</strong> — low, medium, high, max, x-high</li></ul><p>The one detail you have to read carefully: <strong>the tokenizer changed.</strong> The same input text now maps to roughly 1.0–1.35× more tokens on Sonnet 5 than on Sonnet 4.6, depending on content type. Anthropic set the introductory price so the transition is “roughly cost-neutral” from 4.6, but if you’re comparing raw dollar-per-token numbers against your old budget spreadsheet, you’ll be surprised. Audit token counts before you hard-cutover in production.</p><h3>The benchmark picture — with the caveats it deserves</h3><p>This is where most of the launch-day writeups have gotten sloppy. Different sources are reporting different numbers for Sonnet 5 on benchmarks like SWE-Bench Pro, Terminal-Bench 2.1, and OSWorld-Verified — and the disagreements come from two things you have to hold in your head:</p><p><strong>Different agent harnesses produce different scores.</strong> On the official <a href="https://www.tbench.ai/leaderboard/terminal-bench/2.1">Terminal-Bench 2.1 leaderboard</a>, Claude Opus 4.8 scores <strong>74.6% with the Terminus 2 agent</strong> but <strong>78.9% with Claude Code</strong>. Same model, same benchmark, different harness — nearly 5 percentage points of gap. If a comparison claim says “X beats Y” and doesn’t specify the harness, it’s meaningless.</p><p><strong>Vendor-run vs standardized numbers diverge.</strong> Anthropic’s own <a href="https://www.anthropic.com/claude-sonnet-5-system-card">system card</a> reports Sonnet 5 at 63.2% on SWE-Bench Pro and Opus 4.8 at 69.2% — measured on Anthropic’s own tuned agent harness. Scale’s standardized SWE-Bench Pro leaderboard, which runs every model through <em>identical</em> scaffolding, has GPT-5.4 leading the public set at 59.1%, and the best Claude entry at 51.9% (Opus 4.6, thinking mode). These aren’t the same benchmark in any practical sense.</p><p>The honest way to read the situation:</p><ul><li><strong>From Anthropic’s own materials</strong>: Sonnet 5 is a meaningful step up from Sonnet 4.6 and lands close to Opus 4.8 on the benchmarks Anthropic prioritizes. Opus 4.8 still wins on the hardest coding problems, and Anthropic explicitly recommends it for maximum accuracy where cost isn’t the constraint.</li><li><strong>From the standardized cross-vendor leaderboards</strong>: Sonnet 5 isn’t listed yet on either Terminal-Bench 2.1’s official leaderboard (tbench.ai) or Scale’s standardized SWE-Bench Pro leaderboard as of writing. Any “Sonnet 5 beats X model” claim is currently based on vendor-run numbers that aren’t directly comparable to competitor scores.</li></ul><p>Wait a couple of weeks. The standardized leaderboards will fill in and the picture will get clearer.</p><h3>The real change is selectable effort</h3><p>The feature nobody’s talking about enough: Sonnet 5 exposes <strong>five effort levels</strong> — low, medium, high, max, x-high. Higher effort = more thinking tokens = higher accuracy = higher cost. You pick per request.</p><p>This changes model selection more than the release itself did.</p><p>The old question was “which model?” The new question is “which model at which effort level?” And per Anthropic’s own framing in the launch post, users can now “adjust the effort level to find the right balance of cost and performance” <em>between Sonnet 5 and Opus 4.8</em>. In other words, the two-tier decision has softened into a knob you turn per task.</p><p>Rough mental model:</p><ul><li><strong>Low/medium effort Sonnet 5</strong> — the vast majority of production agentic work</li><li><strong>High effort Sonnet 5</strong> — where you’d previously have reached for Opus 4.7 or 4.8</li><li><strong>Max/x-high Sonnet 5</strong> — check whether Opus 4.8 at medium would be cheaper for the same target accuracy</li></ul><p>If you weren’t doing per-request cost analysis before, you probably should be now.</p><h3>Where Opus 4.8 still wins (per Anthropic itself)</h3><p>The launch post is explicit: <strong>Opus 4.8 remains the recommended model for higher accuracy on the hardest problems</strong> — the kind of subtle judgment calls and deep research where the tail-risk of a wrong answer is expensive. Anthropic isn’t positioning Sonnet 5 as an Opus replacement.</p><p>Two other places Opus 4.8 still leads clearly:</p><ul><li><strong>Cybersecurity work.</strong> Anthropic explicitly notes that Sonnet 5 has a “much lower ability to perform dangerous cybersecurity tasks” than the current Opus models. For legitimate security research where model capability matters, Opus 4.8 (or higher) is the recommended tier.</li><li><strong>Anywhere accuracy at the tail matters more than cost.</strong> The 6-point SWE-Bench Pro gap in Anthropic’s own reporting is real. If you’re paying for reliability on frontier-difficulty problems, that gap justifies the price difference.</li></ul><p>That’s a real market. It’s just narrower than the market Opus 4.8 owned last week.</p><h3>What I actually recommend</h3><p>If you’re already on Sonnet 4.6, this is a straightforward upgrade — same base price after the introductory period, better performance, but audit your tokenizer math first.</p><p>If you’re paying for Opus 4.8 across the board, run a bake-off. Take five or ten of your real production tasks, run them through Sonnet 5 at medium and high effort, and see if the quality gap is what you’re paying 2.5× more per token for. For most workloads that aren’t at the frontier of difficulty, the answer will be no.</p><p>If you’re on the free tier and didn’t notice anything change, that’s fine — your default just quietly upgraded, and you’re getting the year’s biggest step forward in agentic mid-tier capability for zero dollars.</p><h3>Why I stopped caring about the launch-week benchmark race</h3><p>The uncomfortable truth about model launches is that the first 72 hours of benchmark reporting are almost always a mess. Third-party blogs conflate models, quote scores from mismatched harnesses, and repeat each other’s numbers without checking primary sources. I know this because my own first-impressions post yesterday did some of the same thing.</p><p>The reliable move is to wait a week, let the official leaderboards catch up, and evaluate on your own tasks. Everything else is telephone.</p><p>What’s <em>not</em> subject to telephone, and what’s actually important:</p><ul><li><strong>Sonnet 5 is 40–60% cheaper than Opus 4.8</strong>, with an introductory rate that lasts through August</li><li><strong>Anthropic frames the two models as one cost-performance curve</strong>, not two tiers</li><li><strong>The effort-level knob is now a real dimension of model selection</strong></li><li><strong>The tokenizer change is a small operational catch</strong> you should audit before switching production</li></ul><p>That’s the story you can defend. The rest — the specific benchmark numbers, the “mid-tier beat flagship” narrative — get clearer over the next couple of weeks when the standardized leaderboards fill in with Sonnet 5 entries.</p><p>Until then: test on your own workloads, don’t trust launch-week benchmark quotes, and enjoy the fact that Anthropic just made the cheaper tier meaningfully more capable at a moment when the whole industry is pushing agents into production.</p><h3>Sources cited in this post</h3><ul><li>Anthropic official launch: <a href="https://www.anthropic.com/news/claude-sonnet-5">anthropic.com/news/claude-sonnet-5</a></li><li>Claude Sonnet 5 system card: <a href="https://www.anthropic.com/claude-sonnet-5-system-card">anthropic.com/claude-sonnet-5-system-card</a></li><li>Terminal-Bench 2.1 official leaderboard: <a href="https://www.tbench.ai/leaderboard/terminal-bench/2.1">tbench.ai/leaderboard/terminal-bench/2.1</a></li><li>SWE-Bench Pro standardized leaderboard (Scale): <a href="https://labs.scale.com/leaderboard/swe_bench_pro_public">labs.scale.com/leaderboard/swe_bench_pro_public</a></li><li>SWE-Bench Verified leaderboard: <a href="https://www.swebench.com/">swebench.com</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29e2acb6478e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Row vs Columnar Databases: Why the Same Query Can Run 100× Faster (or Slower)]]></title>
            <link>https://medium.com/@amaan2000mohd/row-vs-columnar-databases-why-the-same-query-can-run-100-faster-or-slower-8eff9c945555?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eff9c945555</guid>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[oltp-vs-olap]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 09:30:56 GMT</pubDate>
            <atom:updated>2026-06-23T09:30:56.295Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An engineer’s guide to the architectural choice that separates Postgres from Snowflake, MySQL from ClickHouse, and OLTP from analytics — with a clear decision framework at the end.</em></p><h3>The Mystery That Sends Every Engineer Down This Rabbit Hole</h3><p>Here’s a scenario that’s repeated itself in engineering teams thousands of times.</p><p>You have a Postgres table with 50 million rows of order data. You run:</p><pre>SELECT region, SUM(amount), COUNT(*)<br>FROM orders<br>WHERE created_at &gt;= &#39;2025-01-01&#39;<br>GROUP BY region;</pre><p>It takes 28 seconds. You add indexes. You partition the table. You bump the instance size. You finally get it down to 12 seconds.</p><p>Then a colleague mentions they ran the same query against the same data exported to ClickHouse. It returned in 180 milliseconds. On a <em>smaller</em> machine.</p><p>That’s not a difference in tuning. It’s not a difference in hardware. It’s a difference in <strong>how data is physically laid out on disk</strong> — and that single architectural choice explains roughly half of the database landscape you’ll touch in your career.</p><p>This post unpacks that choice. By the end you’ll understand why Postgres is fast at some things and slow at others, why Snowflake is the opposite, and how to confidently pick the right tool for any workload.</p><h3>The One-Sentence Difference</h3><p><strong>Row-oriented databases store all the columns of a single row together. Columnar databases store all the rows of a single column together.</strong></p><p>That’s it. That’s the entire architectural choice. Every other property — compression, query speed, write performance, what each is “good at” — flows downstream from this one decision about byte order on disk.</p><p>Let me make that concrete. Imagine a tiny table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XqDZUwtQW7x1mnpkQnZQA.png" /></figure><p>In a <strong>row-oriented</strong> database, the bytes on disk are laid out like this:</p><pre>[1, Alice, EU, 120][2, Bob, US, 85][3, Carol, EU, 200][4, Dave, US, 95]</pre><p>All the values for row 1 sit next to each other on disk. Then all the values for row 2. And so on.</p><p>In a <strong>columnar</strong> database, the same data is laid out like this:</p><pre>[1, 2, 3, 4][Alice, Bob, Carol, Dave][EU, US, EU, US][120, 85, 200, 95]</pre><p>All the values for the id column sit next to each other. Then all the values for the name column. And so on.</p><p>This rearrangement looks trivial. It is not. It changes almost every performance characteristic of the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*hzb_cFlcTBEqJ5io4J9FeQ.png" /><figcaption><em>Same table, two disk layouts. In row-oriented format, the amber “amount” column is scattered every 4 bytes. In columnar format, it’s contiguous at the end.</em></figcaption></figure><h3>Row-Oriented: Optimized for “Give Me This Specific Row”</h3><p>Row-oriented is the original design. Postgres, MySQL, Oracle, SQL Server, SQLite — all of these store data row-by-row. There’s a reason: most database workloads from the 1970s through the 2000s were operational. They looked like this:</p><ul><li>Find the user with id = 42 and update their email</li><li>Insert a new order</li><li>Delete this expired session</li><li>Show me the complete customer record for account 1234</li></ul><p>Every one of these queries needs the <em>complete record</em> for a specific row. Row-oriented storage makes that trivially fast — the database seeks to the row’s location on disk and reads everything in one I/O operation. All columns are right there, contiguous, ready to go.</p><p>This is what people mean when they say a database is “good at OLTP” (Online Transaction Processing). The workload is:</p><ul><li>High concurrency (many simultaneous users)</li><li>Many small transactions (one row at a time)</li><li>Mix of reads and writes</li><li>Each operation touches a few rows but typically all their columns</li></ul><p>Row-oriented storage maps onto this pattern beautifully. Writes go to the end of the table (or into a page somewhere) as a single contiguous block. Reads grab the whole row in one shot. Indexes accelerate lookups by row identifier.</p><p>What row-oriented databases are <em>not</em> good at is the kind of query in our opening scenario: scan millions of rows, only look at 2–3 columns, aggregate. Here’s why.</p><h3>Columnar: Optimized for “Aggregate Across Millions of Rows”</h3><p>Columnar storage is the design behind every modern analytical database: Snowflake, BigQuery, Redshift, ClickHouse, DuckDB, Vertica, Druid. The query that takes 28 seconds in Postgres returns in milliseconds in any of these — not because their engineers are smarter, but because the storage layout matches the query pattern.</p><p>Walk through our example query again:</p><pre>SELECT region, SUM(amount), COUNT(*)<br>FROM orders<br>WHERE created_at &gt;= &#39;2025-01-01&#39;<br>GROUP BY region;</pre><p>To answer this, the database needs to read four columns: region, amount, created_at, and effectively a row count. It does not need id, name, email, address, phone, metadata, or any of the other 40 columns the orders table probably has.</p><p>In a row-oriented database, all of those columns are interleaved with the ones you care about. Reading “just” the four columns you need actually means reading the entire table — there’s no way to skip the other 40 because they’re sitting between the bytes you want.</p><p>In a columnar database, each column lives in its own contiguous block on disk. The database reads exactly the four columns you asked for and ignores the rest. On a 50-million-row table with 40 columns, that’s a 90% reduction in I/O before any other optimization kicks in.</p><p>But the storage layout isn’t the whole story. Columnar storage compounds with three other techniques that together produce the order-of-magnitude wins.</p><h3>Why Columnar Wins at Analytics: The Three Compounding Wins</h3><h3>1. Compression That Actually Works</h3><p>Column data is <em>homogeneous</em>. The region column contains thousands of values like &quot;EU&quot;, &quot;US&quot;, &quot;APAC&quot; — repeated millions of times. The status column has maybe 5 distinct values. The created_at column has timestamps that are mostly close together.</p><p>When you store homogeneous data together, you can compress it aggressively. Run-length encoding turns “EU, EU, EU, EU, EU” into “EU × 5.” Dictionary encoding maps each distinct value to a small integer. Delta encoding stores created_at values as offsets from the previous value, which compresses to a few bits each.</p><p>Real-world compression ratios on columnar storage are routinely <strong>10–30×</strong> versus row-oriented. For observability data (highly repetitive), they’re often higher. This means:</p><ul><li>Storage costs drop by an order of magnitude</li><li>I/O drops by the same factor (less data to read)</li><li>More data fits in RAM, so cache hit rates climb</li></ul><p>Row-oriented databases can’t get these ratios because each row mixes incompatible data types. You can’t run-length encode “1, Alice, EU, 120” — the values have nothing in common.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Pb1O90KjDt4CVfklYjZSOA.png" /><figcaption><em>Same column, before and after run-length encoding. Repetitive values become a handful of entries.</em></figcaption></figure><h3>2. Vectorized Execution</h3><p>Once data is columnar, the query engine can process it in <em>vectors</em> — typically 1024 or 2048 values at a time — rather than row by row. This matters because modern CPUs are designed to process arrays of values in parallel using SIMD (Single Instruction, Multiple Data) instructions.</p><p>A row-oriented database typically processes one row at a time: load row, extract columns, run predicate, accumulate result, repeat. Each iteration has function call overhead, branch prediction misses, and cache pressure.</p><p>A columnar database processes a vector at a time: load 1024 amount values, multiply by a vector of 1024 booleans (the predicate result), sum the result. The CPU executes this in tight, pipelined loops that are 10-100× faster per row of input.</p><p>This is why columnar databases like DuckDB feel impossibly fast on a laptop. Same hardware, fundamentally different execution model.</p><h3>3. Predicate Push-Down and Statistics</h3><p>Columnar formats (Parquet, ORC, the internal formats of Snowflake/ClickHouse/etc.) store <em>statistics</em> at the block level: min, max, count, distinct values. Before reading any actual data, the engine can check whether a block might contain matching rows.</p><p>For your queryWHERE created_at &gt;= &#39;2025-01-01&#39;, the engine reads block statistics first. Blocks whose created_at max is 2024-12-15 Get skipped entirely. On a partitioned dataset, entire partitions get skipped. On S3, the engine makes range requests for only the bytes it actually needs.</p><p>Row-oriented databases can do <em>some</em> of this with indexes, but indexes are expensive to maintain, and they only cover what you knew to index ahead of time. Columnar statistics cover <em>every</em> column automatically, without you doing anything.</p><p>These three wins compound. Less data to read (compression) + faster execution per byte (vectorization) + reading fewer bytes (push-down) = analytical queries that are 50–100× faster on the same hardware.</p><h3>Why Row Wins at OLTP: The Three Reasons That Matter</h3><p>Columnar doesn’t win at everything. For transactional workloads, row-oriented is dramatically better. Three reasons.</p><h3>1. Single-Row Reads Are Trivially Fast</h3><p>To read the user with id = 42 From a row-oriented database: seek to the row&#39;s location, read it, done. One disk I/O, one cache line, one transaction.</p><p>To do the same in a columnar database: read the id column to find which position 42 is at, then read each other column at that position to assemble the row. That&#39;s N separate reads for an N-column table. The columnar database is worse than row-oriented for this — by a factor of however many columns the table has.</p><h3>2. Inserts and Updates Are Cheap</h3><p>Inserting a single row in a row-oriented database: append the row to a page, update indexes, commit. Fast and simple.</p><p>Inserting a single row in a columnar database: split the row into N column values, append each one to its column’s storage block. The columnar database now has to maintain N storage blocks instead of one row. Worse, columnar blocks are usually compressed — adding a value forces decompression, append, recompression. Most columnar databases handle this by buffering writes and applying them in batches, but that adds latency.</p><p>For workloads where inserts arrive one at a time and need to be visible immediately, row-oriented is strictly better.</p><h3>3. Concurrent Updates Don’t Fight</h3><p>Row-oriented databases use row-level locking. Two transactions updating two different rows don’t block each other. This is the entire foundation of modern OLTP.</p><p>Columnar databases typically don’t update in place — they append a tombstone and write a new version. This works at scale but adds complexity and latency that you don’t want for an authoritative source of truth in a high-concurrency application.</p><h3>The Hybrids: Why the Lines Are Blurring</h3><p>The clean row-vs-columnar dichotomy was true ten years ago. It’s less true now. Several databases have started mixing the two models.</p><p><strong>Postgres + pg_duckdb / Citus columnar</strong> — Postgres can now run analytical queries against columnar data inside the same database that handles your OLTP. Mixed workload, single system.</p><p><strong>ClickHouse</strong> has added experimental support for row-based engines for cases where its columnar default doesn’t fit.</p><p><strong>SingleStore (MemSQL), TiDB, CockroachDB</strong> — modern distributed databases that store some tables in row form and others in columnar form, depending on access pattern. Same query language, same transaction guarantees.</p><p><strong>Snowflake</strong> transparently stores data in micro-partitions that are columnar internally but can be addressed as if they were rows for single-row lookups.</p><p><strong>DuckDB</strong> is columnar but supports OLTP-style single-row operations well enough for embedded use cases.</p><p>The takeaway: the boundary is moving. But the underlying tradeoffs are not — they’re just being hidden behind smarter query engines. Understanding the architecture still tells you why a query is fast or slow.</p><h3>The Decision Framework</h3><p>Now the practical part. Which one do you actually pick?</p><h3>Pick row-oriented (Postgres, MySQL, etc.) when:</h3><ul><li>Your workload is <strong>transactional</strong> — many small reads and writes per second, each touching a single row or a few rows</li><li>You need <strong>point queries</strong> by primary key: “fetch user 42”, “update order #1234”</li><li>You need <strong>strong consistency</strong> for concurrent writes (banking, inventory, anything where two clients fighting over the same row matters)</li><li>Your data has <strong>moderate volume</strong> — up to a few hundred million rows or a few hundred GB per table</li><li>You need a <strong>mature ecosystem</strong> — ORMs, BI integrations, hosting providers, hires who know it</li></ul><h3>Pick columnar (Snowflake, BigQuery, ClickHouse, DuckDB, etc.) when:</h3><ul><li>Your workload is <strong>analytical</strong> — queries that aggregate over millions of rows, touch a few columns, return small result sets</li><li>Your data is <strong>large</strong> — hundreds of GB to petabytes, where I/O reduction from columnar compression actually matters</li><li>Your queries follow predictable <strong>SELECT … WHERE … GROUP BY</strong> patterns over a stable schema</li><li>You need <strong>fast aggregations</strong> more than fast single-row lookups</li><li>You can tolerate <strong>slightly stale data</strong> (columnar databases often batch ingest)</li></ul><h3>When in doubt, here’s the lazy-but-correct heuristic:</h3><ul><li>Are you building an <strong>application</strong> (users, sessions, orders, transactions)? → Start with Postgres</li><li>Are you building a <strong>dashboard or report or analytics product</strong>? → Start with a columnar database</li><li>Are you building <strong>both</strong>? → Run Postgres for the application, copy to columnar (or use pg_duckdb) for the analytics</li></ul><p>You almost never want a row-oriented database doing analytical work at scale, or a columnar database doing OLTP. Each is bad at the other’s job in a way that no amount of tuning will fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQuIkyCh4nqdRCcP4zFvNQ.png" /><figcaption><em>The decision matrix. Workload type on one axis, data scale on the other — four quadrants, four recommended categories of database.</em></figcaption></figure><h3>The Mental Model That Sticks</h3><p>Here’s the framing I’ve found most useful when explaining this to teammates:</p><p><strong>Row-oriented databases are organized like filing cabinets.</strong> Each row is a folder. To find a specific record, you grab the right folder and everything’s there. To compute statistics across all records, you have to open every folder and read everything inside.</p><p><strong>Columnar databases are organized like spreadsheets.</strong> Each column is a sheet. To compute statistics on one column, you pull the sheet and you’re done. To find a complete record, you have to cross-reference the same row position across every sheet.</p><p>Both work. Which one is “better” depends entirely on whether you mostly read folders or mostly compute statistics.</p><h3>A Closing Thought</h3><p>The reason this matters more than ever is that data has gotten cheap enough to store, and the queries we want to ask have gotten more analytical. Twenty years ago every database was row-oriented because most queries were transactional. Today every team eventually needs both — application data flowing in from row-oriented stores and analytical answers flowing out of columnar engines.</p><p>You don’t have to memorize benchmark numbers or vendor names. You just have to remember the one-sentence difference at the top of this post: row-oriented stores rows together, columnar stores columns together. Everything else — the compression, the speed, the tradeoffs — falls out of that one architectural choice.</p><p>Once you see it, every database you encounter slots into the right mental box. And the next time someone asks “why is Postgres slow for this query?” or “do we really need Snowflake?”, you’ll know exactly where to look for the answer.</p><p><em>If you’ve made the wrong choice and lived through the migration — or made the right choice and avoided it — I’d love to hear what tipped the call.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eff9c945555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ClickStack: The Observability Stack That Makes Datadog Look Absurd at Scale]]></title>
            <link>https://medium.com/@amaan2000mohd/clickstack-the-observability-stack-that-makes-datadog-look-absurd-at-scale-f0c22d9fed12?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0c22d9fed12</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[otel]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[traceability]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 18:35:44 GMT</pubDate>
            <atom:updated>2026-06-17T18:35:44.125Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Lessons from rolling out ClickStack across 15 services — the architecture that makes it cheap, the deployment patterns that actually scale, and the honest tradeoffs nobody warns you about.</em></p><h3>The Observability Bill That Started It</h3><p>Most engineering teams hit the same wall, usually around the time someone on Finance prints out the Datadog quote and asks why it costs more than the team building the product.</p><p>The conversation goes the same way every time. “Why is it so expensive?” Because we’re ingesting a lot of telemetry. “Can we ingest less?” We could, but then we lose visibility. “Can we sample harder?” We already sample. “Is there an alternative?” Yes. “How much engineering work?” <em>Pause.</em></p><p>That pause is where most teams give up and pay whatever the bill says. We didn’t — we evaluated the open-source alternatives before committing — and the answer turned out to be <strong>ClickStack</strong>: an open-source observability stack from ClickHouse that bundles HyperDX (the UI), ClickHouse (the storage and query engine), and a tuned OpenTelemetry Collector into a single deployable system. Launched in May 2025 after ClickHouse acquired HyperDX, it’s now in production at organizations ingesting billions of high-cardinality events per day.</p><p>I rolled this out across 15 internal services over the past few months. This post is the deep-dive I wish someone had handed me on day one: the architecture, the deployment lessons, and the comparison against Datadog (and the open-source alternatives) that I actually trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFTBrCy1SlfTlHjAvZLI9w.png" /><figcaption>ClickHouse / HyperDX</figcaption></figure><h3>What ClickStack Actually Is</h3><p>ClickStack is three components glued together with strong defaults:</p><ol><li><strong>OpenTelemetry Collector</strong> — a pre-configured OTel Collector that knows how to ingest logs, metrics, and traces over OTLP and write them to ClickHouse using batched, optimized inserts.</li><li><strong>ClickHouse</strong> — the high-performance columnar analytical database that stores everything. The same database powering analytics workloads at Uber, Cloudflare, eBay, and basically every company that’s hit “billions of events per day.”</li><li><strong>HyperDX UI</strong> — a developer-focused observability interface that runs SQL and Lucene-style queries against ClickHouse, with built-in dashboards, alerting, trace exploration, and session replay.</li></ol><p>The pitch is straightforward: <strong>OpenTelemetry-native ingestion, ClickHouse-level query performance, an engineer-friendly UI</strong>, all open source, deployable anywhere, with cost structures an order of magnitude cheaper than proprietary SaaS at scale.</p><p>But what makes it interesting isn’t any single component. It’s the architectural decision sitting underneath the whole thing: treating observability as an analytical workload, not a logging workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdBmgsGW4Lz0noMWdEZ5zA.png" /><figcaption><em>ClickStack architecture overview</em></figcaption></figure><h3>The Architecture Bet: “Wide Events” on a Columnar Engine</h3><p>Traditional observability platforms grew up around three separate signal types — logs (text), metrics (numbers), and traces (call graphs) — each with its own storage backend, query language, and retention model. You’d run Elasticsearch for logs, Prometheus for metrics, Jaeger for traces, and stitch them together in your head during incidents.</p><p>ClickStack rejects that split. Everything is a <strong>wide event</strong> — a context-rich row in a ClickHouse table with whatever fields the application sends. A log line is a wide event. A trace span is a wide event with extra fields. A metric data point is a wide event with a numeric value. The schema is flexible because ClickHouse natively supports JSON columns, dynamic typing, and schema-on-read.</p><p>Three architectural properties of ClickHouse make this work in ways that surprise people:</p><h3>1. Columnar storage with absurd compression</h3><p>ClickHouse stores data column-by-column, like a warehouse. For observability data — which is overwhelmingly repetitive (same hostnames, same service names, same log levels, same trace IDs) — compression ratios of 10–20x are routine. We’re storing 2 weeks of high-cardinality production telemetry in roughly the same disk footprint that a comparable Elasticsearch deployment would have needed for one week of the same data, and at meaningfully lower cost than what SaaS providers charge for equivalent retention.</p><h3>2. Parallel, vectorized query execution</h3><p>ClickHouse uses every CPU core on every node, executing queries in vectorized batches. A WHERE service=&#39;checkout&#39; AND status_code &gt;= 500 GROUP BY user_id Query across 30 days of trace data — the kind of query that takes 8 seconds in Elasticsearch — returns in under a second on a moderately-sized cluster.</p><h3>3. Native JSON without schema migrations</h3><p>Observability schemas evolve constantly. New services add new fields, instrumentation libraries change attribute names, and business contexts get attached to spans. ClickHouse’s native JSON type means new fields appear automatically as columns the moment they’re ingested — no migration, no schema change, no downtime.</p><p>The compound effect: an observability platform that stores more data, queries it faster, and adapts to schema changes without operational pain — at a fraction of the cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EH3f2j7_0nOOKSqC7d-mQ.png" /></figure><h3>What I Learned Deploying It for 15 Services</h3><p>The marketing brochure says “deploy ClickStack and you’re done.” The reality is more nuanced. Here’s what actually worked and what we got wrong.</p><h3>Configuration over service registry</h3><p>The instinct from teams coming from service-mesh-heavy environments is to set up a service registry, dynamic configuration, and per-service overrides. We skipped all of that. The whole stack is configured via a single repository of YAML files — one per service — that defines the OTel Collector pipelines, sampling policies, and retention rules.</p><p>Why this matters: when you have 15 services and you’re rolling out observability across them, the bottleneck is not “how do I dynamically reconfigure.” It’s “what does this service actually emit, and is it correct.” A flat, version-controlled config tree makes the answer obvious. We could review observability changes in PRs the same way we review code changes.</p><h3>Tail sampling, not head sampling</h3><p>The default for most teams is head sampling — decide at the start of a trace whether to keep it, before you know if anything interesting happened. This is fast but you lose the traces that actually mattered (errors, slow requests, edge cases) at the same rate as the boring ones.</p><p>Tail sampling — decide at the end of the trace, after you can see the full call graph — is dramatically better. You keep 100% of errors, 100% of slow requests over a threshold, and a small percentage of the rest. ClickStack’s bundled Collector supports tail sampling out of the box; you configure it once and forget it. Storage costs dropped roughly 70% compared to our initial head-sampled deployment, with zero loss of useful traces.</p><h3>TTL-based retention, set per data class</h3><p>Not all telemetry is equal. We set:</p><ul><li><strong>Logs</strong>: 14 days (cheap to keep, sometimes investigated late)</li><li><strong>Metrics</strong>: 90 days (small footprint, useful for capacity planning)</li><li><strong>Traces (errors)</strong>: 30 days</li><li><strong>Traces (sampled normal)</strong>: 7 days</li><li><strong>Session replays</strong>: 7 days</li></ul><p>ClickHouse TTLs handle this automatically. Old data drops off without intervention, and storage cost stays predictable.</p><h3>Instrumentation patterns per language</h3><p>Different stacks need different instrumentation strategies, and the OpenTelemetry SDKs vary in maturity:</p><ul><li><strong>Python (FastAPI)</strong>: auto-instrumentation works well; the opentelemetry-instrumentation-fastapi package covers HTTP, requests to other services, and database calls without code changes. Manual spans where business logic mattered.</li><li><strong>Node (Express)</strong>: similar story, auto-instrumentation handles 80% of the work.</li><li><strong>Go</strong>: manual instrumentation is the norm. The Go OTel SDK is good but not auto-instrumenting. Plan for it in PRs.</li><li><strong>Java (Spring)</strong>: the Java agent is excellent — drop in the JAR, set environment variables, you get traces automatically across Spring Boot, JDBC, HTTP clients, and Kafka.</li></ul><p>Document this once for your team. The biggest delay in any observability rollout is the long tail of “how do I instrument <em>this</em> service” questions that have already been answered five times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*uPet98ctcsDNCZvBQ_Oq7w.gif" /><figcaption><em>HyperDX — SQL and Lucene queries side by side</em></figcaption></figure><h3>The “single OTel Collector or one per service” question</h3><p>You’ll face this early. The answer: a small fleet of OTel Collectors deployed as a DaemonSet (Kubernetes) or sidecar (VMs), feeding into a centralized “gateway” Collector that handles tail sampling and routing to ClickHouse. This gives you locality (apps send to localhost), backpressure isolation, and a single point to apply sampling policies.</p><p>Trying to point every service directly at a single shared Collector becomes a bottleneck and a single point of failure faster than you’d expect.</p><h3>ClickStack vs Datadog vs SigNoz vs Grafana</h3><p>Where ClickStack actually fits in the landscape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-P6rof23eMvUQ8_cB14E3A.png" /></figure><p>The honest summary:</p><ul><li><strong>Datadog wins</strong> if you have the budget, don’t want to operate anything, and need the broadest ecosystem of integrations on day one.</li><li><strong>Grafana stack wins</strong> if you’ve already standardized on it, have the ops team to maintain three storage backends, and don’t need session replay or unified wide events.</li><li><strong>SigNoz wins</strong> for small teams who want ClickHouse-backed observability and a friendly out-of-box experience, but its schema and UI lag behind ClickHouse engine improvements.</li><li><strong>ClickStack wins</strong> when you’re hitting the bill wall on Datadog, have (or can hire) people comfortable with ClickHouse, and want the cleanest open-source path to unified observability.</li></ul><p>The cost difference is well documented: independent operators report 10–50x cost reduction vs Datadog at 1–5 TB/day ingestion. When we ran the comparison ourselves before committing, the Datadog quote came in at roughly an order of magnitude higher than what we ended up paying for self-managed ClickStack infrastructure at equivalent scale. That gap is why this conversation keeps happening across the industry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*-Ev0KMe2S0ZM5ndkyHf4-Q.gif" /></figure><h3>Where ClickStack Doesn’t Shine (Be Honest)</h3><p>It’s not a free lunch. The honest tradeoffs:</p><h3>1. You’re operating ClickHouse now</h3><p>ClickHouse is a fantastic database. It’s also a real database with operational responsibilities — replica configuration, part merges, TTL tuning, ZooKeeper or Keeper for coordination, backups, version upgrades. If your team doesn’t have anyone who’s comfortable reading ClickHouse system tables and tuning a MergeTree, you&#39;ll either learn fast or pay a managed ClickHouse provider.</p><p>Managed ClickHouse Cloud (from ClickHouse Inc.) removes most of this pain, but at a cost. It’s still cheaper than Datadog, but the gap narrows.</p><h3>2. The ecosystem is younger than Datadog’s</h3><p>Datadog has thousands of pre-built integrations. ClickStack relies on OpenTelemetry’s ecosystem, which is excellent and growing fast but doesn’t cover every niche vendor. If you rely on a SaaS that only exports metrics via a Datadog-specific agent, you’ll need to build a bridge.</p><h3>3. Alerting is less mature</h3><p>HyperDX has alerting built in, and it works, but it’s not as battle-tested as Datadog’s. Complex multi-signal alert conditions, escalation policies tied to PagerDuty/Opsgenie integrations, and on-call rotations are areas where Datadog still has the polish advantage. ClickStack is closing the gap but isn’t there yet.</p><h3>4. The learning curve is real</h3><p>If your team has spent years building muscle memory in Datadog’s DSL or Grafana’s LogQL, switching to ClickHouse SQL + HyperDX’s Lucene syntax requires retraining. Plan for a 4–6 week ramp where productivity dips before it climbs.</p><h3>5. Session replay is good, but new</h3><p>The HyperDX session replay feature is genuinely impressive, but it’s newer than most production-grade alternatives. If session replay is a tier-1 feature for your team (e.g., you’re a frontend-heavy product team), evaluate it carefully against more mature options first.</p><h3>When to Reach for ClickStack</h3><p><strong>Use it when:</strong></p><ul><li>Your observability bill is a regular topic in budget reviews</li><li>You’re already running ClickHouse for something else (the operational marginal cost is near zero)</li><li>You want unified logs/metrics/traces/sessions without stitching three backends together</li><li>You need to query high-cardinality data fast and SaaS is choking on it</li><li>You’re building AI agent workflows for observability (the MCP server is a real win here)</li></ul><p><strong>Don’t use it when:</strong></p><ul><li>You have a small team, no ClickHouse experience, and limited budget for managed services</li><li>Your scale is small enough that Datadog’s free or low-tier pricing covers you</li><li>You depend heavily on Datadog-specific integrations you can’t replace</li><li>Your priority is “set it and forget it” with zero operational burden</li></ul><h3>A Closing Thought</h3><p>The observability industry has spent a decade convincing engineering teams that the only way to get production-grade visibility is to write large checks to one of three vendors. That was true when storing 10 TB of structured logs cost a fortune. It isn’t anymore.</p><p>ClickHouse changed the economics. ClickStack just made those economics accessible to teams that don’t want to build their own observability platform from scratch. If you can operate one more stateful service, the math works out. If your team is already running ClickHouse for analytics, the marginal cost of adding observability to it is essentially zero.</p><p>bash</p><pre># Quick start: full stack via Docker Compose<br>git clone https://github.com/ClickHouse/ClickStack<br>cd ClickStack<br>docker compose up</pre><p>You can have an end-to-end OTLP pipeline running locally in 5 minutes. Point a test service at it, send some traces, open HyperDX at localhost:8080, and you’ll know within an afternoon whether this belongs in your stack.</p><p>The hard part isn’t the technology. The hard part is convincing the team that the SaaS line item you’re about to take on — or the one you’re already paying — isn’t worth what it costs at scale. For most teams at production scale, it absolutely isn’t.</p><p><em>If you’ve migrated from a SaaS observability platform to ClickStack — or considered it and decided otherwise — I’d love to hear what tipped the call and what surprised you in the deployment.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0c22d9fed12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DuckDB: The In-Process Database Quietly Eating Pandas, Snowflake, and Half Your Data Stack]]></title>
            <link>https://medium.com/@amaan2000mohd/duckdb-the-in-process-database-quietly-eating-pandas-snowflake-and-half-your-data-stack-6b97fd786349?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b97fd786349</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 11:47:08 GMT</pubDate>
            <atom:updated>2026-06-12T11:47:08.588Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Sub-second analytics on 100-million-row datasets, no server, no ETL, no cluster. A deep dive on why DuckDB has become the default tool for analytical work that fits on one machine — which turns out to be most analytical work.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozYv6HaL4SjgBTnJzGQKUA.png" /></figure><h3>The 100-Million-Row Pandas Crash That Started It</h3><p>Every data person’s origin story with DuckDB is roughly the same.</p><p>You’re working in a Jupyter notebook. You load a Parquet file with pd.read_parquet(). It&#39;s 8 GB on disk. Pandas tries to load it into memory, your laptop swaps, the kernel dies, and you spend the next 20 minutes wondering whether to (a) chunk the file manually, (b) spin up a Spark cluster for what should be a 5-minute analysis, or (c) export to your warehouse and write SQL there.</p><p>Then someone tells you to try DuckDB:</p><pre>import duckdb<br>duckdb.sql(&quot;SELECT category, COUNT(*) FROM &#39;big_file.parquet&#39; GROUP BY 1&quot;).show()</pre><p>Three seconds. No crash. No cluster. No warehouse. The query ran <em>directly against the file</em>, in your Python process, using every CPU core you have.</p><p>That moment — for a lot of people — was the conversion point. DuckDB has quietly eaten enough of the data world that “should we use DuckDB here?” is now the <em>default</em> question on data-engineering RFCs, not the contrarian one. 37,500+ GitHub stars. A growing list of teams that replaced their Snowflake bills with a single VM. And a still-surprising amount of working data infrastructure that fits in a single pip install.</p><p>This post is a tour of what DuckDB actually is, why the architecture matters, the four real patterns where it wins, and the honest tradeoffs. Whether you’re a data engineer, a backend developer adding analytics features, or an architect trying to make sense of where this fits, by the end you’ll know whether DuckDB belongs in your stack.</p><h3>What DuckDB Actually Is</h3><p>DuckDB is an <strong>in-process, columnar OLAP database</strong>. Each of those words is doing work.</p><ul><li><strong>In-process</strong> — there’s no server. No daemon. No port. You pip install duckdb and it runs <em>inside</em> your Python (or R, or Node, or Rust, or browser-via-WASM) process. SQLite for analytics, in every sense that matters.</li><li><strong>Columnar</strong> — data is stored column-by-column, not row-by-row. Aggregations and analytical queries hit only the columns they need. This is the same architectural choice that makes Snowflake and BigQuery fast at scale; DuckDB brings it to your laptop.</li><li><strong>OLAP</strong> — Online Analytical Processing. It’s optimized for GROUP BY, JOIN, WINDOW, and aggregations across millions to billions of rows. It is <em>not</em> optimized for high-concurrency OLTP — that&#39;s Postgres&#39;s job.</li></ul><p>The killer architectural property is that DuckDB doesn’t need data to be <em>in</em> the database. You can query Parquet files, CSVs, JSON, S3 buckets, Pandas DataFrames, Polars DataFrames, Arrow tables, and (since 2026) Iceberg and Delta Lake catalogs — all directly, with full SQL. No ETL step. No schema migration. No “load data into the database first.”</p><pre>import duckdb<br># Query a CSV<br>duckdb.sql(&quot;SELECT * FROM &#39;sales.csv&#39; WHERE region = &#39;EMEA&#39; LIMIT 10&quot;).show()<br># Query a Parquet file on S3 - no download<br>duckdb.sql(&quot;SELECT COUNT(*) FROM &#39;s3://my-bucket/events/2026/*.parquet&#39;&quot;).show()<br># Query a Pandas DataFrame directly<br>import pandas as pd<br>df = pd.read_csv(&#39;customers.csv&#39;)<br>duckdb.sql(&quot;SELECT country, COUNT(*) FROM df GROUP BY country&quot;).show()<br># Join across all three<br>duckdb.sql(&quot;&quot;&quot;<br>    SELECT c.country, SUM(s.amount) as total<br>    FROM df c<br>    JOIN &#39;sales.csv&#39; s ON c.id = s.customer_id<br>    JOIN &#39;s3://my-bucket/events/*.parquet&#39; e ON s.id = e.sale_id<br>    GROUP BY c.country<br>&quot;&quot;&quot;).show()</pre><p>That last query — joining a DataFrame, a local CSV, and a partitioned Parquet dataset on S3 — would have been a multi-hour ETL exercise a few years ago. With DuckDB, it’s one SQL statement.</p><h3>How It Actually Works (The Architecture Worth Understanding)</h3><p>DuckDB’s speed isn’t magic — it’s the result of a few deliberate engineering decisions that compound. Understanding them helps you predict when it’ll be fast (almost always) and when it won’t (rare, but real).</p><h3>Vectorized execution</h3><p>Most traditional databases process data one row at a time. For analytical workloads — GROUP BY, Aggregations, window functions — this is enormously wasteful. DuckDB processes data in <strong>vectors</strong> (typically 1024 or 2048 values at a time), in tight loops that the CPU can pipeline and SIMD-accelerate.</p><p>The practical impact: queries that touch millions of rows often run an order of magnitude faster than the same query against a row-oriented database, even when both are running on the same hardware against the same data.</p><h3>Multi-threading by default</h3><p>DuckDB uses every CPU core on your machine automatically. There’s no SET parallel = TRUE to remember. A query against a 50-million-row Parquet file on an 8-core laptop runs across all 8 cores in parallel, with the scheduler partitioning work and merging results without your involvement.</p><p>Compare this to Pandas, which is single-threaded by default and requires libraries like Dask or Polars to parallelize. With DuckDB, parallelism is the default, and you have to opt out if you want serial execution.</p><h3>Spill-to-disk for memory pressure</h3><p>If a query needs more memory than you have RAM, DuckDB automatically spills intermediate state to disk. Sorts, hash joins, and aggregations that would crash Pandas with an OutOfMemoryError instead get slower — but they finish. On a 16 GB laptop, queries against 100 GB+ datasets are routinely possible, just not instant.</p><h3>Columnar storage (when you persist data)</h3><p>DuckDB has its own native storage format — a single .duckdb file that&#39;s columnar, compressed, and supports ACID transactions. You can use it as a real database, not just an ephemeral query engine:</p><pre>import duckdb<br># Create a persistent database<br>con = duckdb.connect(&#39;analytics.duckdb&#39;)<br>con.execute(&quot;CREATE TABLE events AS SELECT * FROM &#39;raw_events.parquet&#39;&quot;)<br>con.execute(&quot;CREATE INDEX idx_user ON events(user_id)&quot;)<br># Later, in another process<br>con = duckdb.connect(&#39;analytics.duckdb&#39;, read_only=True)<br>result = con.execute(&quot;SELECT COUNT(*) FROM events&quot;).fetchone()</pre><p>The .duckdb file is portable — copy it to another machine, open it, and your data is there. Backups are cp. There&#39;s no server state to lose.</p><h3>Push-down optimization across formats</h3><p>When you query a Parquet file with a WHERE clause, DuckDB doesn&#39;t load the whole file. It reads the Parquet column statistics, skips row groups that don&#39;t match, and reads only the columns you actually reference. For partitioned datasets, it skips entire partitions. For S3, it makes range requests for only the bytes it needs.</p><p>The result: querying a 50 GB Parquet dataset on S3 with WHERE region = &#39;EU&#39; AND year = 2025 might read only a few hundred MB of actual data over the wire. This is the same kind of optimization that makes BigQuery and Snowflake fast — DuckDB does it from your laptop.</p><h3>Does DuckDB re-read data with every query?</h3><p>This is the question that comes up about ten minutes into anyone’s first DuckDB project, and the honest answer is: <em>it depends on which of three patterns you’re using.</em></p><h3>Pattern 1: Direct queries against files</h3><pre>duckdb.sql(&quot;SELECT SUM(amount) FROM &#39;orders.parquet&#39;&quot;)</pre><p>DuckDB <strong>opens the file with every query.</strong> It doesn’t keep it loaded between queries. This sounds expensive, but rarely is, because of two things:</p><ul><li><strong>Push-down</strong> (covered above) means each query reads only the columns and row groups it actually needs — often 5–10% of the file, not the whole thing.</li><li><strong>The OS file system cache</strong> keeps recently-read bytes in RAM. The second query against the same file is dramatically faster than the first because the OS hands the pages back instantly.</li></ul><p>For Parquet on local disk or warm S3 ranges, this is the right pattern. The “re-read” cost is mostly fictional.</p><h3>Pattern 2: External database scanners (Postgres, MySQL, etc.)</h3><pre>duckdb.sql(&quot;ATTACH &#39;host=db.local dbname=app&#39; AS pg (TYPE postgres);&quot;)<br>duckdb.sql(&quot;SELECT SUM(amount) FROM pg.orders WHERE region = &#39;EU&#39;&quot;)</pre><p>This is where the “re-read” concern is real. DuckDB pushes down what it can, but the data still has to be fetched from Postgres over the wire on <strong>every query</strong>. If you run 100 queries against the same Postgres table, you fetch the data 100 times.</p><p>For ad-hoc exploration, this is fine. For repeated analytical workloads, you want pattern 3.</p><h3>Pattern 3: Load once, query many times</h3><pre>con = duckdb.connect(&#39;analytics.duckdb&#39;)<br># Pay the conversion cost ONCE<br>con.execute(&quot;&quot;&quot;<br>    CREATE TABLE orders AS<br>    SELECT * FROM postgres_scan(&#39;host=db.local&#39;, &#39;public&#39;, &#39;orders&#39;)<br>&quot;&quot;&quot;)<br># Every subsequent query reads from DuckDB&#39;s own columnar storage<br>con.execute(&quot;SELECT region, SUM(amount) FROM orders GROUP BY region&quot;)<br>con.execute(&quot;SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id&quot;)</pre><p>After the CREATE TABLE, The data lives in DuckDB&#39;s native columnar format inside analytics.duckdb. There&#39;s no Postgres round-trip per query. There&#39;s no row-to-column conversion. Every query reads pre-vectorized data from disk, hitting the buffer pool on repeats.</p><p>The tradeoff is freshness — your DuckDB copy is a snapshot. Most teams refresh it on a schedule (every hour, every night) that matches how stale they can tolerate the data being.</p><h3>The mental model</h3><p>DuckDB has three personalities depending on how you use it:</p><ol><li><strong>Query engine</strong> — points at external files or databases, reads on every query, convenient for exploration.</li><li><strong>Cache layer</strong> — load external data into a .duckdb file once, query many times, refresh on a schedule.</li><li><strong>Primary store</strong> — write data into DuckDB’s columnar format from the start, no conversion ever.</li></ol><p>Most production deployments use #3 for hot analytical data and #1 only for exploratory work. Pattern #2 is the migration step from a row-oriented source.</p><h3>The SQL Dialect You’ll Actually Enjoy Writing</h3><p>DuckDB’s SQL dialect is a quietly delightful piece of design. It supports the full standard — window functions, recursive CTEs, lateral joins, complex grouping — but it also adds quality-of-life extensions that make analytical SQL less painful.</p><h3>GROUP BY ALL and SELECT * EXCLUDE</h3><p>The annoying parts of SQL get fixed:</p><pre>-- Old SQL: list every non-aggregated column in GROUP BY<br>SELECT region, product, country, COUNT(*), SUM(amount)<br>FROM sales<br>GROUP BY region, product, country;<br>-- DuckDB: just GROUP BY ALL<br>SELECT region, product, country, COUNT(*), SUM(amount)<br>FROM sales<br>GROUP BY ALL;<br>-- And exclude columns easily<br>SELECT * EXCLUDE (internal_id, debug_info) FROM events;</pre><h3>FROM-first query syntax</h3><p>You can put the FROM clause first — useful when writing queries iteratively or letting LLMs generate them:</p><pre>FROM &#39;events.parquet&#39; SELECT user_id, COUNT(*) GROUP BY user_id;</pre><h3>Friendly type casts and string functions</h3><p>:: for casting, LIKE with case-insensitive ILIKE, full regex support, STRING_AGG, LIST and STRUCT types for nested data — the dialect feels written by people who actually write SQL.</p><h3>Extensions for everything else</h3><p>DuckDB ships with a built-in extensions system. Need to query Parquet? INSTALL parquet. Iceberg tables? INSTALL iceberg. S3? INSTALL httpfs. Postgres tables? INSTALL postgres_scanner. JSON, spatial, full-text search, ML scoring — there&#39;s an extension for each, and you install them in one SQL statement.</p><pre>INSTALL httpfs;<br>LOAD httpfs;<br>SET s3_region=&#39;us-east-1&#39;;<br>SELECT COUNT(*) FROM &#39;s3://my-bucket/events/*.parquet&#39;;</pre><h3>The Ecosystem Around DuckDB</h3><p>DuckDB itself is the engine. What makes it genuinely viable as production infrastructure — and not just a notebook toy — is the ecosystem that’s grown around it. Two pieces are worth knowing about by name.</p><p><strong>DuckLake</strong> is DuckDB’s lakehouse layer — a catalog stored in any standard SQL database (Postgres, MySQL, SQLite, or DuckDB itself), with data files in Parquet on object storage. Time travel, ACID transactions, schema evolution — the things that make Apache Iceberg useful, without the JVM and the operational complexity. For teams who tried Iceberg and bounced off, DuckLake is the sane alternative.</p><pre>ATTACH &#39;ducklake:postgres:host=db.local dbname=catalog&#39;<br>  AS lake (DATA_PATH &#39;s3://my-lake/&#39;);<br>CREATE TABLE lake.events (id BIGINT, ts TIMESTAMP, payload JSON);<br>SELECT * FROM lake.events AT (VERSION =&gt; 42);  -- time travel</pre><p><strong>pg_duckdb</strong> is a Postgres extension that runs the DuckDB engine inside a Postgres process. It transparently routes analytical queries to DuckDB and OLTP queries to Postgres — meaning you can finally run GROUP BY over millions of rows in your transactional database without watching it crawl. If your &quot;I should move analytical queries off Postgres&quot; plan has been on the backlog for two years, pg_duckdb may quietly retire it.</p><pre>CREATE EXTENSION pg_duckdb;<br>-- This uses DuckDB&#39;s columnar engine, against data living in Postgres<br>SELECT date_trunc(&#39;month&#39;, created_at) AS month, SUM(amount)<br>FROM orders<br>GROUP BY 1;</pre><p>Beyond those two, there’s DuckDB-WASM (full SQL in the browser), client libraries for every major language, and a growing list of integrations with BI tools, orchestrators, and dbt. The pace of ecosystem development has been fast enough that “Is there a way to do X with DuckDB?” is increasingly answered with “Yes, there’s an extension for that.”</p><h3>Where DuckDB Wins: Four Real Patterns</h3><h3>1. The Pandas Replacement</h3><p>The simplest, most common use. You have data in CSV, Parquet, or a DataFrame, and you want to do real analytical work — group, join, aggregate, window — without watching Pandas die.</p><pre>import duckdb<br># A 50-line Pandas chain replaced with one SQL query<br>result = duckdb.sql(&quot;&quot;&quot;<br>    WITH ranked AS (<br>        SELECT<br>            customer_id,<br>            amount,<br>            ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn<br>        FROM &#39;transactions.parquet&#39;<br>    )<br>    SELECT * FROM ranked WHERE rn &lt;= 3<br>&quot;&quot;&quot;).df()  # Returns a Pandas DataFrame</pre><p>DuckDB’s .df() Integration means it slots into existing Pandas workflows. You use Pandas for what it&#39;s good at (display, ML pipeline integration), and DuckDB for what it&#39;s good at (the actual analytical work).</p><h3>2. Embedded Analytics in SaaS Products</h3><p>You’re building a SaaS product. Customers want dashboards. The traditional answer is: export data to Snowflake/BigQuery, run dbt, embed Metabase. Three services, three failure points, several seconds of latency per query.</p><p>The DuckDB alternative: schedule Parquet exports from Postgres to S3, query them with DuckDB inside your API. Single-digit-millisecond response times. No warehouse. No BI tool license. For a 5-person SaaS team shipping analytics for the first time, this is genuinely the right architecture.</p><h3>3. Replacing Your Cloud Warehouse for SME Workloads</h3><p>This is the one that surprises people. Teams have replaced Snowflake or BigQuery bills with single-VM DuckDB setups for 50–200 GB workloads — and reported 80% cost reductions. The setup: Parquet files on S3, DuckDB on a single beefy VM (or even a Lambda), DuckLake or Iceberg for the catalog.</p><p>This isn’t right for everyone. Warehouses still win on multi-team concurrency, ecosystem maturity, and large-scale workloads (north of a few TB of actively-queried data). But for the long tail of small- and medium-sized analytical workloads — which is <em>most</em> analytical workloads — DuckDB is now genuinely competitive on TCO and faster on most queries.</p><h3>4. Edge and Local Analytics</h3><p>DuckDB-WASM runs DuckDB in the browser. Full SQL, full performance, querying remote Parquet files directly from the user’s browser. This unlocks a category of analytics products (interactive data explorers, in-browser dashboards) that previously required server-side query backends.</p><p>For desktop apps, CLIs, internal tools, and AI agents that need to “look at the data” without a network round-trip, DuckDB at the edge is the right call.</p><h3>DuckDB vs The Alternatives</h3><p><strong>DuckDBPandasSnowflake/BigQuerySpark</strong>DeploymentIn-processIn-processManaged cloudClusterConcurrencySingle-processSingle-userMulti-tenantMulti-tenantScaleUp to ~1 TB on a single nodeUp to RAMPetabytePetabyteQuery languageSQLDataFrame APISQLSQL + DataFrameCostFree (compute only)Free$$$$$Best atLocal + embedded analyticsSmall-data ML pipelinesMulti-team enterprise warehousingTruly massive ETLWorst atHeavy concurrency, OLTPAnything &gt; RAMCost-per-query at small scaleAnything small enough not to need a cluster</p><p>The short version: <strong>DuckDB is the default for analytical workloads that fit on one machine.</strong> Spark stays relevant when you actually have petabytes. Snowflake/BigQuery stay relevant for multi-team enterprise environments. Pandas stays relevant for small DataFrames inside Python pipelines. DuckDB is everywhere in between — and “everywhere in between” turns out to be most of the actual analytics work happening in the world.</p><h3>Where DuckDB Doesn’t Shine (Be Honest)</h3><p>It’s not the right answer for everything. The honest limitations:</p><h3>1. Concurrency is its weak spot</h3><p>In-process means single-process. Multi-user shared analytics over the same database file is awkward — you typically end up with read-only replicas or one-file-per-tenant patterns. If your use case is “100 analysts querying the same dataset simultaneously,” you want a server-based warehouse instead.</p><h3>2. It’s not an OLTP database</h3><p>DuckDB optimizes for analytical reads, not transactional writes. Single-row inserts are slow compared to Postgres. Heavy update workloads are painful. Don’t use it as your application’s primary database — use it alongside Postgres for the analytical workload.</p><h3>3. Memory pressure on huge JOINs</h3><p>DuckDB spills to disk gracefully, but very large hash JOINs can still saturate I/O and slow to a crawl. For most workloads this never matters; for the workload that crosses the line, you’ll know.</p><h3>4. Smaller ecosystem than the giants</h3><p>Compared to Postgres or Snowflake, DuckDB has fewer mature integrations, fewer enterprise BI tool connectors, and fewer “battle-tested in production at Fortune 500” case studies. This gap is closing fast — but if your buying committee wants ten reference customers in your industry, DuckDB may not have them yet.</p><h3>5. Operational maturity is still maturing</h3><p>Backup, point-in-time recovery, role-based access control, audit logging — the operational features that enterprise databases ship with by default are still being filled in. The roadmap is clearly headed here, but if you need every enterprise checkbox today, you’ll find gaps.</p><h3>When to Reach for DuckDB</h3><p><strong>Use DuckDB when:</strong></p><ul><li>You’re doing analytical work in Python, R, or Node and Pandas is hitting walls</li><li>You’re building a SaaS product with embedded analytics features</li><li>Your warehouse bill is disproportionate to your data volume</li><li>You need to query Parquet/CSV/JSON files directly without ETL</li><li>You’re building local/desktop/browser analytics tools</li><li>You want analytical queries inside your Postgres database (via pg_duckdb)</li><li>You’re prototyping a data pipeline before committing to heavier infrastructure</li></ul><p><strong>Don’t use DuckDB when:</strong></p><ul><li>You have genuine petabyte-scale workloads — Spark/Snowflake still win</li><li>You need true multi-user concurrency today (wait for Quack to mature)</li><li>You need OLTP — use Postgres</li><li>Your organization has compliance requirements that haven’t yet been audited against DuckDB</li><li>You need a mature BI tool ecosystem with deep DuckDB integration — getting better, not there yet</li></ul><h3>A Closing Thought</h3><p>The shift DuckDB represents isn’t really about a new database. It’s about the realization that a huge fraction of “big data” wasn’t actually that big — it just <em>felt</em> big because the tools we had treated 10 GB the same way they treated 10 TB.</p><p>DuckDB bets that modern laptops and single VMs are absurdly powerful, that columnar execution and vectorized engines extract orders of magnitude more performance from existing hardware than row-oriented databases ever did, and that “warehouse-class” performance no longer requires a warehouse.</p><p>That bet has paid off. DuckDB isn’t the future of analytics. It’s the present.</p><p>bash</p><pre>pip install duckdb</pre><p>python</p><pre>import duckdb<br>duckdb.sql(&quot;SELECT &#39;hello&#39; AS greeting&quot;).show()</pre><p>Five seconds. You’re already running it.</p><p><em>If you’ve put DuckDB into production — or evaluated it and chose otherwise — I’d love to hear the call you made and what surprised you most.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b97fd786349" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Authorization Code Is a Mess (and How OpenFGA Fixes It)]]></title>
            <link>https://medium.com/@amaan2000mohd/why-your-authorization-code-is-a-mess-and-how-openfga-fixes-it-09e61b8ca29f?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e61b8ca29f</guid>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[openfga]]></category>
            <category><![CDATA[permission]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 10:31:48 GMT</pubDate>
            <atom:updated>2026-06-08T10:31:48.425Z</atom:updated>
            <content:encoded><![CDATA[<p>From 400-line can_user_do() Functions for a relationship graph—Google Zanzibar&#39;s open-source descendant, with hands-on code.</p><h3>The Permissions Table That Becomes Your Worst Enemy</h3><p>Every backend starts the same way. You ship the MVP with three roles — admin, user, guest. A roles table, a user_roles join table, maybe a permissions enum somewhere. Life is good.</p><p>Then the requirements start arriving.</p><p>“Owners can edit but not delete. Editors can edit but not invite. Viewers can comment but not edit. And actually, document owners should also be able to invite — but only if they’re also workspace admins.”</p><p>Six months later, your permissions.py has a 400-line can_user_do() function full of nested ifs. Every new feature ships with a new column on user_permissions. Every PR review includes the line &quot;did you remember to check authz?&quot; Your QA team can&#39;t write tests for permission edge cases because nobody knows what the rules even are anymore.</p><p>Then a customer says: “I want to share this document with my whole team — but only the engineering sub-team — and revoke access if they leave the team.”</p><p>And you realize: you don’t have a permissions problem. You have a <em>data model</em> problem. Permissions in real applications aren’t roles. They’re <strong>relationships</strong>.</p><p>This is exactly what Google figured out around 2016 when they built Zanzibar — the internal authorization system that powers Drive, YouTube, Photos, and most of their other consumer products. Zanzibar models permissions as relationship tuples and answers billions of “can this user do this thing?” checks per second across Google’s entire stack.</p><p>OpenFGA is the open-source, Linux Foundation-backed implementation of those ideas. It’s a CNCF incubating project, used in production by Grafana, Docker, Canonical, and a growing list of others. And if you’ve been hand-rolling permissions tables for years, it might be the cleanest infrastructure decision you make this quarter.</p><p>Let’s get into it.</p><h3>What “Relationship-Based Access Control” Actually Means</h3><p>The mental shift takes about 15 minutes to internalize, but it changes how you think about authorization permanently.</p><p><strong>RBAC</strong> (Role-Based Access Control) — the model most apps start with — says: “Alice has the role <em>editor</em>, and editors can update documents.” Permissions are properties of roles. Roles are properties of users.</p><p><strong>ABAC</strong> (Attribute-Based Access Control) — the model many compliance-heavy apps end up with — says: “Alice can update this document because her department matches the document’s department AND the current time is during business hours AND her clearance level is at least 3.” Permissions are computed from attributes.</p><p><strong>ReBAC</strong> (Relationship-Based Access Control) — the Zanzibar/OpenFGA approach — says: “Alice can update document:budget because Alice is a member of group:finance, and group:finance has the <em>editor</em> relation to document:budget.” Permissions are derived from the graph of relationships between users, groups, and resources.</p><p>The killer property of ReBAC is <strong>composability</strong>. You don’t enumerate every (user, resource, permission) triple. You declare <em>what relationships imply what permissions</em>, and then add small relationship facts to the system. The implications are:</p><ul><li>Alice is a member of the engineering team.</li><li>The engineering team owns the backend repository.</li><li>Owners of a repository can merge pull requests.</li><li>Therefore, Alice can merge pull requests on the backend repository.</li></ul><p>Three facts. Many derived permissions. Add a fourth fact (“Alice leaves the engineering team”), and every implied permission disappears automatically. No cascading SQL deletes. No “did we forget to revoke that?” bugs.</p><p>That’s the model. Now let’s see what it looks like in OpenFGA’s actual DSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQuFNPEOjGCWzzGH6WkVvg.jpeg" /></figure><h3>Five Minutes With the OpenFGA DSL</h3><p>OpenFGA has its own modeling language — a small, readable DSL that describes types, relations, and how relations compose. Here’s a complete model for a Google-Docs-style application:</p><pre>model<br>  schema 1.1<br>type user<br>type group<br>  relations<br>    define member: [user]<br>type folder<br>  relations<br>    define owner: [user]<br>    define viewer: [user, group#member] or owner<br>type document<br>  relations<br>    define parent: [folder]<br>    define owner: [user]<br>    define editor: [user, group#member] or owner<br>    define viewer: [user, group#member] or editor or viewer from parent</pre><p>Read that out loud, and most of it explains itself. A few things worth pointing out:</p><ul><li><strong>[user, group#member]</strong> — this is the &quot;userset&quot; trick. It means the relation accepts both individual users <em>and</em> &quot;members of a group.&quot; This is how Zanzibar-style systems handle group-based access in a single line.</li><li><strong>or owner</strong> — Anyone who is an owner is also automatically an editor. No need to write that as a separate tuple.</li><li><strong>viewer from parent</strong> — inheritance. If you&#39;re a viewer of the parent folder, you&#39;re a viewer of the document. This single line replaces what would be hundreds of lines of recursive SQL.</li></ul><p>That model — twelve lines — describes a permission system that would take 500+ lines of application code to implement correctly.</p><h3>How Relationships Become Facts</h3><p>The model is the schema. The actual permissions live in <strong>relationship tuples</strong> — facts of the form (user, relation, object):</p><pre>user:alice          owner    document:budget-2026<br>user:bob            viewer   document:budget-2026<br>group:finance#member editor  document:budget-2026<br>user:carol          member   group:finance<br>document:budget-2026 parent  folder:finance-docs<br>user:dave           owner    folder:finance-docs</pre><p>Six tuples and the implied permissions cover a real scenario:</p><ul><li>Alice owns the document directly.</li><li>Bob can view it directly.</li><li>Any member of the finance group can edit it (which means Carol can, because she’s a member).</li><li>Dave owns the parent folder, so he can view (and through inheritance, also edit) the document.</li></ul><p>Now ask: <em>Can Carol edit the budget?</em> OpenFGA traverses the graph: Carol → member of finance → finance#member is editor of document → yes.</p><p>Ask: <em>Can someone outside finance view it?</em> No. The graph terminates.</p><p>Ask: <em>List all users who can view the budget.</em> OpenFGA returns Alice, Bob, Carol, Dave, and anyone else reachable via the relationship graph.</p><p>This is the API that replaces your can_user_do() function.</p><h3>Hands-On: Zero to Working in 10 Minutes</h3><p>OpenFGA runs as a service. The fastest way to try it is Docker:</p><pre>docker run -p 8080:8080 -p 8081:8081 -p 3000:3000 openfga/openfga run</pre><p>That starts the API on port 8080, the gRPC interface on 8081, and the visual Playground on 3000. The Playground is genuinely good — paste a DSL model, write some tuples, and click around to test permission checks visually.</p><p>Then install the SDK. Here’s Python:</p><pre>pip install openfga-sdk</pre><p>A complete working example — create a store, load a model, write some tuples, and check permissions:</p><pre>import asyncio<br>from openfga_sdk import OpenFgaClient, ClientConfiguration<br>from openfga_sdk.client.models import (<br>    ClientTuple, ClientCheckRequest, ClientWriteRequest<br>)<br>async def main():<br>    config = ClientConfiguration(api_url=&quot;http://localhost:8080&quot;)<br>    async with OpenFgaClient(config) as fga:<br>        # 1. Create a store<br>        store = await fga.create_store({&quot;name&quot;: &quot;docs-app&quot;})<br>        fga.set_store_id(store.id)<br>        # 2. Write the authorization model (using the JSON form here for brevity)<br>        model = await fga.write_authorization_model({<br>            &quot;schema_version&quot;: &quot;1.1&quot;,<br>            &quot;type_definitions&quot;: [<br>                {&quot;type&quot;: &quot;user&quot;},<br>                {<br>                    &quot;type&quot;: &quot;document&quot;,<br>                    &quot;relations&quot;: {<br>                        &quot;owner&quot;: {&quot;this&quot;: {}},<br>                        &quot;editor&quot;: {&quot;union&quot;: {&quot;child&quot;: [<br>                            {&quot;this&quot;: {}},<br>                            {&quot;computedUserset&quot;: {&quot;relation&quot;: &quot;owner&quot;}}<br>                        ]}},<br>                        &quot;viewer&quot;: {&quot;union&quot;: {&quot;child&quot;: [<br>                            {&quot;this&quot;: {}},<br>                            {&quot;computedUserset&quot;: {&quot;relation&quot;: &quot;editor&quot;}}<br>                        ]}}<br>                    },<br>                    &quot;metadata&quot;: {&quot;relations&quot;: {<br>                        &quot;owner&quot;:  {&quot;directly_related_user_types&quot;: [{&quot;type&quot;: &quot;user&quot;}]},<br>                        &quot;editor&quot;: {&quot;directly_related_user_types&quot;: [{&quot;type&quot;: &quot;user&quot;}]},<br>                        &quot;viewer&quot;: {&quot;directly_related_user_types&quot;: [{&quot;type&quot;: &quot;user&quot;}]}<br>                    }}<br>                }<br>            ]<br>        })<br>        fga.set_authorization_model_id(model.authorization_model_id)<br>        # 3. Write some relationship tuples<br>        await fga.write(ClientWriteRequest(writes=[<br>            ClientTuple(user=&quot;user:alice&quot;, relation=&quot;owner&quot;,  object=&quot;document:budget&quot;),<br>            ClientTuple(user=&quot;user:bob&quot;,   relation=&quot;editor&quot;, object=&quot;document:budget&quot;),<br>            ClientTuple(user=&quot;user:carol&quot;, relation=&quot;viewer&quot;, object=&quot;document:budget&quot;),<br>        ]))<br>        # 4. Check permissions<br>        for user, relation in [<br>            (&quot;user:alice&quot;, &quot;viewer&quot;),   # owner → editor → viewer (implied)<br>            (&quot;user:bob&quot;,   &quot;viewer&quot;),   # editor → viewer (implied)<br>            (&quot;user:carol&quot;, &quot;editor&quot;),   # viewer only - should be False<br>            (&quot;user:dave&quot;,  &quot;viewer&quot;),   # no relation at all<br>        ]:<br>            resp = await fga.check(ClientCheckRequest(<br>                user=user, relation=relation, object=&quot;document:budget&quot;<br>            ))<br>            print(f&quot;{user} can {relation} document:budget → {resp.allowed}&quot;)<br>asyncio.run(main())</pre><p>Output:</p><pre>user:alice can viewer document:budget → True<br>user:bob   can viewer document:budget → True<br>user:carol can editor document:budget → False<br>user:dave  can viewer document:budget → False</pre><p>That’s the whole loop: model, tuples, check. Three concepts, three API calls.</p><p>A few things worth flagging:</p><ol><li><strong>The DSL is preferred for humans; the JSON form is what the API accepts.</strong> The OpenFGA CLI translates between them. In production you usually keep the model as a .fga file in your repo and use the CLI or a build step to convert it.</li><li><strong>check is the hot-path API.</strong> It answers a single permission question in single-digit milliseconds. OpenFGA&#39;s whole architecture is optimized to make check fast.</li><li><strong>There are other endpoints worth knowing</strong>: list_objects (&quot;which documents can Alice view?&quot;), list_users (&quot;who can edit this document?&quot;), expand (&quot;show me the relationship graph for this permission&quot;). These are the queries that show up in admin UIs, audit logs, and &quot;share this document with...&quot; dialogs.</li></ol><h3>Three Real Patterns You’ll Hit</h3><h3>1. Multi-Tenant SaaS</h3><p>Almost every SaaS hits this: organizations contain teams, teams contain users, and resources belong to organizations. OpenFGA models this cleanly:</p><pre>type organization<br>  relations<br>    define admin: [user]<br>    define member: [user] or admin<br>type project<br>  relations<br>    define organization: [organization]<br>    define owner: [user]<br>    define contributor: [user, organization#member] or owner<br>    define viewer: [user, organization#member] or contributor</pre><p>Add one tuple — (user:eve, member, organization:acme) — and Eve immediately has contributor and viewer access to every project owned by Acme. Remove that tuple, and her access disappears across the entire tenant. No JOIN chains. No &quot;did we propagate the org change?&quot; bugs.</p><h3>2. Resource Sharing With Inheritance</h3><p>The Google Drive pattern — folders contain documents, share a folder, everyone gets the documents inside:</p><pre>type folder<br>  relations<br>    define parent: [folder]<br>    define viewer: [user] or viewer from parent<br>    define editor: [user] or editor from parent<br>type document<br>  relations<br>    define parent: [folder]<br>    define viewer: [user] or viewer from parent<br>    define editor: [user] or editor from parent</pre><p>Three lines of DSL handle arbitrary folder nesting. The viewer from parent Recursion terminates naturally when a folder has no parent tuple.</p><h3>3. Conditional / Context-Aware Access</h3><p>Need access to depend on something that <em>isn’t</em> a relationship — a time of day, an IP range, a token claim? OpenFGA supports two patterns:</p><ul><li><strong>Conditions</strong> — first-class predicates attached to a tuple. The classic example is time-limited grants:</li></ul><pre>model<br>  schema 1.1<br>type user<br>type document<br>  relations<br>    define viewer: [user with non_expired_grant]<br>condition non_expired_grant(current_time: timestamp, grant_time: timestamp, grant_duration: duration) {<br>  current_time &lt; grant_time + grant_duration<br>}</pre><p>A viewer tuple now carries grant_time grant_duration. Every check passes current_time as context. Expired grants automatically stop granting access — no cron job needed to clean up.</p><ul><li><strong>Contextual tuples</strong> — relationships you pass <em>only for this check</em>, derived from request context (JWT claims, headers, IP). Useful when the user’s group membership lives in their access token rather than your database.</li></ul><p>Both let you push ABAC-style policies into a ReBAC system without dual-stack complexity.</p><h3>Where OpenFGA Doesn’t Shine (Be Honest)</h3><p>No system is free. The honest tradeoffs:</p><h3>1. You’re running another service</h3><p>OpenFGA is a stateful service backed by Postgres, MySQL, or SQLite. That’s another deployment, another set of dashboards, another HA story. For small apps with simple permissions, this is overkill. Run it when your if user.role == chain has become a recurring source of bugs.</p><h3>2. Latency adds up</h3><p>A single check Call is fast (~1-5 ms locally, more across availability zones). If a single API request needs to check 50 permissions, that&#39;s 50-250 ms just for authz. OpenFGA&#39;s batch_check and list_objects Endpoints exist precisely to avoid this — use them. Don&#39;t loop check calls in application code.</p><h3>3. The model is the new schema</h3><p>In a hand-rolled permissions system, your “model” lives in the application code, and changes ship with PRs. With OpenFGA, your model is a separate artifact that needs versioning, migrations, and review. This is <em>better</em> in the long run (your authz is testable and inspectable), but it’s a discipline shift. Teams that don’t treat the FGA model as production code end up with the same mess they had before, just in a different file.</p><h3>4. ReBAC isn’t the right hammer for every nail</h3><p>If your authorization is genuinely role-based and small (“admin / user / guest, no nuance”), forcing ReBAC on it is over-engineering. The win shows up when your permissions are inherently relational — sharing, hierarchies, group memberships, multi-tenancy. If your app doesn’t have those patterns, RBAC is fine.</p><h3>5. Eventual consistency on tuple writes</h3><p>OpenFGA defaults to a “higher consistency” mode for recent writes, but the underlying architecture is built around the assumption that authorization checks read from a slightly stale view. For most apps, this is invisible. For apps where a permission grant must take effect immediately for the next request (some financial flows, some content publishing flows), you’ll need to use the HigherConsistency flag explicitly — and accept the small performance cost.</p><h3>6. The ecosystem is smaller than that of competitors</h3><p>Compared to AWS Cognito, Auth0, or even open-source competitors like Casbin, OpenFGA has fewer community plugins, fewer hosted offerings, and fewer Stack Overflow answers. The official SDKs are solid (Go, Node, Python, Java, .NET), and the Playground is excellent — but if you’re looking for a giant ecosystem, this isn’t it. Yet.</p><h3>When to Reach For OpenFGA</h3><p>The honest version:</p><p><strong>Reach for it when:</strong></p><ul><li>Your permissions have inherently relational structure (sharing, hierarchies, group membership, multi-tenancy).</li><li>You have 3+ distinct resource types, each with its own permission rules, and the rules are starting to interact.</li><li>“Who has access to X?” or “What can user Y see?” are real product features, not just admin queries.</li><li>You want authorization changes to be reviewable artifacts, not buried in pull requests.</li><li>You’re building enterprise features (SCIM provisioning, granular sharing, audit trails) that customers will pay extra for.</li></ul><p><strong>Don’t reach for it when:</strong></p><ul><li>Your permissions are genuinely simple and likely to stay that way.</li><li>You’re a solo dev or a two-person team with a roadmap that doesn’t include authorization complexity.</li><li>Your existing system is working and you have no recurring authz bugs.</li></ul><h3>A Closing Thought</h3><p>The reason authorization is so often a mess in real codebases isn’t that engineers are sloppy. It’s that authorization <em>looks</em> like a code problem and <em>is</em> a data-model problem. Once you frame it that way — once you accept that permissions are relationships, not properties — the answer almost designs itself.</p><p>Zanzibar was Google’s answer. OpenFGA is the version the rest of us get to use. It’s open-source, CNCF-backed, production-tested at Grafana and Docker, and free to try in 10 minutes.</p><pre>docker run -p 8080:8080 -p 3000:3000 openfga/openfga run</pre><p>Open the Playground at localhost:3000, paste the document model above, and play with it. By the time your coffee’s done, you’ll know whether it belongs in your stack.</p><p><em>If you’ve migrated from hand-rolled permissions to OpenFGA — or evaluated it and chose otherwise — I’d love to hear what tipped the call.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e61b8ca29f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL 18: A Feature-by-Feature Deep Dive for Engineers Who Actually Run It]]></title>
            <link>https://medium.com/@amaan2000mohd/postgresql-18-a-feature-by-feature-deep-dive-for-engineers-who-actually-run-it-4e4e07a85a26?source=rss-c6be102fe838------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4e07a85a26</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[trending]]></category>
            <dc:creator><![CDATA[Mohd Amaan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 08:51:18 GMT</pubDate>
            <atom:updated>2026-06-08T08:51:18.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Async I/O, UUIDv7, skip scan, virtual generated columns, RETURNING OLD/NEW, OAuth 2.0, statistics-preserving upgrades, temporal constraints — and the migration gotchas no release-notes summary mentions.</p><h3>Why This Release Matters More Than the Headlines Suggest</h3><p>PostgreSQL 18 (released September 25, 2025) is the kind of release that’s easy to underrate from a tweet. There’s no “Postgres now does X” moment that fits in a headline. What there <em>is</em>, when you actually run it, is a long list of changes that quietly remove pain points you’d stopped noticing — because you’d already worked around them.</p><p>A few examples of what I mean:</p><ul><li>The first major rewrite of Postgres’s I/O subsystem in years, delivering 2–3× faster sequential scans on the workloads that need it most.</li><li>A native uuidv7() function that finally fixes the &quot;random UUIDs destroy your index&quot; problem without a third-party extension.</li><li>B-tree skip scan, which lets composite indexes get used in queries that previously couldn’t touch them.</li><li>Virtual generated columns as the new default — schema-level computed fields that don’t take disk space.</li><li>RETURNING OLD and RETURNING NEW — change-data-capture and audit logging in a single statement.</li><li>Statistics preserved across major-version upgrades, killing the “queries are slow until ANALYZE finishes” post-upgrade incident pattern.</li><li>OAuth 2.0 authentication, finally.</li><li>Temporal constraints (PERIOD, WITHOUT OVERLAPS) — time-range integrity baked into the schema.</li></ul><p>This post walks through every one of those in depth, with working code and the migration gotchas. Whether you’re a backend developer, a DBA, or an architect deciding when to upgrade, by the end you should know exactly which features will impact your stack and which to ignore.</p><p>Let’s get into it.</p><h3>1. Asynchronous I/O (The Big One)</h3><p>For most of Postgres’s history, when a query needed to read a block from disk, the backend issued the read synchronously and waited. The kernel’s readahead would sometimes help on sequential scans, but Postgres itself had no concept of overlapping I/O — one request at a time, one block at a time, with the CPU twiddling its thumbs in between.</p><p>Postgres 18 introduces an Asynchronous I/O (AIO) subsystem. Reads can now be batched, issued in parallel, and completed out of order while the backend keeps doing other useful work. The result is dramatic on I/O-bound workloads — sequential scans, bitmap heap scans, and VACUUM see 2–3× throughput improvements in published benchmarks.</p><p>You configure it with the new io_method parameter:</p><p>sql</p><pre>-- Check what&#39;s currently in use<br>SHOW io_method;<br>-- Options: &#39;sync&#39; (legacy), &#39;worker&#39; (default, cross-platform), &#39;io_uring&#39; (Linux only)<br>ALTER SYSTEM SET io_method = &#39;io_uring&#39;;<br>SELECT pg_reload_conf();</pre><p>The three modes:</p><ul><li><strong>sync</strong> — the legacy synchronous path. Use this if you hit issues with the new code.</li><li><strong>worker</strong> — uses a pool of background I/O worker processes. Cross-platform, the new default.</li><li><strong>io_uring</strong> — uses Linux&#39;s modern io_uring interface. Lowest overhead, highest throughput, but Linux-only and requires a reasonably recent kernel (5.1+ for basic support; 6.x recommended for performance).</li></ul><p>A related parameter to tune isio_workers, which controls the worker pool size when io_method = &#39;worker&#39;. The default is 3; bump it to 8–16 on machines with fast NVMe and lots of concurrent queries.</p><p><strong>Who this matters for</strong>: anything I/O-bound. Analytics workloads, large sequential scans, big VACUUM runs, bulk data loads. OLTP workloads that already fit in shared buffers won&#39;t see as dramatic a win, but they won&#39;t hurt either.</p><p><strong>Gotcha</strong>: io_uring requires liburing to be available at compile time. If you&#39;re using your distro&#39;s Postgres package, check that it was built with --with-liburing. Cloud providers (RDS, Aurora, Cloud SQL) abstract this away from you.</p><h3>2. Native UUIDv7 (Goodbye, Random Index Bloat)</h3><p>This is the feature backend developers have wanted for years.</p><p>The problem with UUIDv4 as a primary key is that values are completely random. Every insert hits a different page of the B-tree index, blowing the cache, causing constant page splits, and generating massive write amplification on the WAL. At scale, a UUIDv4-keyed table is measurably slower than a bigint-keyed one — and the bloat compounds over time.</p><p>UUIDv7 fixes this by encoding a Unix millisecond timestamp into the first 48 bits, then filling the rest with random data. The result is a <em>globally unique UUID</em> (like v4) but <em>monotonically increasing</em> (like a bigserial). Inserts hit the right-hand edge of the index. Page splits drop. Cache hit rates climb.</p><p>Until Postgres 18, you needed an extension like pg_uuidv7 to get this. Now it&#39;s native:</p><pre>-- Generate a UUIDv7<br>SELECT uuidv7();<br>-- 0192b3e8-7c4a-7d8e-9f12-3a8b4c5d6e7f<br>-- Use it as a default<br>CREATE TABLE orders (<br>    id          uuid PRIMARY KEY DEFAULT uuidv7(),<br>    customer_id uuid NOT NULL,<br>    total       numeric(12, 2),<br>    created_at  timestamptz NOT NULL DEFAULT now()<br>);<br>-- Extract the timestamp from a UUIDv7<br>SELECT uuid_extract_timestamp(&#39;0192b3e8-7c4a-7d8e-9f12-3a8b4c5d6e7f&#39;);<br>-- 2025-10-08 14:23:45.018+00</pre><p>That uuid_extract_timestamp() function is genuinely useful — you can sort by primary key and get chronological order, and recover the creation time without a separate column.</p><p><strong>Migration tip</strong>: if you have existing UUIDv4 tables, you don’t need to rewrite them. New rows can use uuidv7() while old rows keep their v4 values. The two coexist in the same column without issue — uuid is just uuid. But for new tables, defaulting to v7 is now the obvious choice.</p><p><strong>Gotcha</strong>: UUIDv7 encodes the creation time. If that timestamp is sensitive (e.g., revealing when a user signed up to anyone with a primary-key value), use UUIDv4 instead. For most internal IDs, this is fine; for public-facing IDs, think twice.</p><h3>3. B-Tree Skip Scan (Your Composite Indexes Just Got Smarter)</h3><p>Imagine you have a multi-tenant SaaS with this index:</p><p>sql</p><pre>CREATE INDEX idx_events_tenant_created ON events (tenant_id, created_at);</pre><p>You run an admin query that doesn’t filter by tenant:</p><pre>SELECT * FROM events<br>WHERE created_at &gt; now() - interval &#39;1 hour&#39;<br>ORDER BY created_at DESC<br>LIMIT 100;</pre><p>In Postgres 17 and earlier, this query can’t use the index. The leading column (tenant_id) isn&#39;t in the predicate, so the planner falls back to a sequential scan. To make it use the index, you&#39;d either reorder the index (and break other queries), add a redundant index on created_at alone, or rewrite the query to enumerate tenants.</p><p>Postgres 18 introduces <strong>skip scan</strong>, which teaches the planner to use the index anyway. Behind the scenes, it constructs a “skip array” — effectively rewriting the query as WHERE tenant_id = ANY(&lt;all distinct tenant_ids&gt;) AND created_at &gt; ... and walking the relevant slices of the index.</p><p>This works best when the skipped leading column is <strong>low cardinality</strong> (a few hundred distinct values, not millions). If you have 50 tenants, skip scan is essentially free. If you have 50 million distinct values in the leading column, the planner will skip the optimization itself.</p><p><strong>No code changes needed.</strong> The planner picks it up automatically. But it’s worth checking EXPLAIN ANALYZE on slow queries after upgrading — some queries that previously did seq scans will quietly start using indexes.</p><p><strong>Index design implication</strong>: This changes the calculus for multi-column index design. The old rule of thumb was “put the most-filtered column first.” With skip scan, <strong>putting the lower-cardinality column first is now generally better</strong> because skip scan can still use the index when the leading column is filtered <em>or</em> skipped. Existing index ordering doesn’t need to change urgently, but new indexes should follow the new heuristic.</p><h3>4. Virtual Generated Columns (Now the Default)</h3><p>Generated columns have existed since Postgres 12, but they were always STORED — the value got computed at write time and persisted to disk. That made reads fast but added write overhead and disk space.</p><p>Postgres 18 introduces VIRTUAL generated columns, which are computed at read time. And — important detail — virtual is now the <strong>default</strong> when you don&#39;t specify STORED VIRTUAL explicitly.</p><p>sql</p><pre>CREATE TABLE products (<br>    id              bigserial PRIMARY KEY,<br>    price_cents     integer NOT NULL,<br>    tax_rate        numeric(4, 4) NOT NULL,</pre><pre>    -- Old way: stored, computed on write, takes disk space<br>    total_stored    numeric(12, 2) GENERATED ALWAYS AS<br>                    ((price_cents / 100.0) * (1 + tax_rate)) STORED,</pre><pre>    -- New way: virtual, computed on read, no disk space<br>    total_virtual   numeric(12, 2) GENERATED ALWAYS AS<br>                    ((price_cents / 100.0) * (1 + tax_rate)) VIRTUAL,</pre><pre>    -- New default: virtual (same as above, just shorter)<br>    total_default   numeric(12, 2) GENERATED ALWAYS AS<br>                    ((price_cents / 100.0) * (1 + tax_rate))<br>);</pre><p><strong>When to use which:</strong></p><ul><li><strong>VIRTUAL</strong> — for derived values you read occasionally and don’t want to pay write/storage cost for. Display formatting, simple arithmetic, computed flags, etc.</li><li><strong>STORED</strong> — for values you read <em>constantly</em>, especially if you want to index them. (Virtual columns <em>cannot be indexed</em> in this release. That’s the biggest limitation to know about.)</li></ul><p><strong>Other limitations</strong>:</p><ul><li>Virtual columns can’t be replicated via logical replication. Only STORED-generated columns can be published.</li><li>Virtual columns can’t be used in foreign keys.</li><li>Virtual columns can’t have a STATISTICS target set.</li></ul><p><strong>Migration gotcha</strong>: if you have existing schemas using bare GENERATED ALWAYS AS (...) syntax without STORED, Those compiled against PG17 with the implicit STORED meaning. After upgrade, the existing columns retain their STORED behavior — but any <em>new</em> generated columns added without STORED will be virtual. This can quietly change behavior for migration tools that recreate schemas. Always be explicit: STORED or VIRTUAL, Never bare.</p><h3>5. RETURNING OLD/NEW (Audit Logs in One Statement)</h3><p>Before Postgres 18, capturing both the old and new values of an updated row took either a trigger, a CTE with a self-join, or two queries. Now RETURNING understands OLD and NEW aliases:</p><p>sql</p><pre>-- Update a user&#39;s tier and capture before/after in one shot<br>UPDATE users<br>SET tier = &#39;enterprise&#39;, updated_at = now()<br>WHERE id = &#39;usr_42&#39;<br>RETURNING<br>    OLD.tier   AS old_tier,<br>    NEW.tier   AS new_tier,<br>    OLD.updated_at AS old_updated_at,<br>    NEW.updated_at AS new_updated_at;</pre><p>This works on INSERT, UPDATE, DELETE, and MERGE. For INSERT, OLD columns are NULL. For DELETE, NEW columns are NULL. For UPDATE and MERGE, Both are populated.</p><p>The killer use case is <strong>audit logging in a single statement</strong>:</p><pre>-- Atomic update + audit log entry, no trigger<br>WITH updated AS (<br>    UPDATE accounts<br>    SET balance = balance - 100<br>    WHERE account_id = &#39;acc_1&#39;<br>    RETURNING<br>        account_id,<br>        OLD.balance AS old_balance,<br>        NEW.balance AS new_balance,<br>        now()       AS changed_at<br>)<br>INSERT INTO audit_log (account_id, old_balance, new_balance, changed_at)<br>SELECT account_id, old_balance, new_balance, changed_at FROM updated;</pre><p>That’s one round trip, atomic, no trigger maintenance. Change Data Capture pipelines that previously needed Debezium or a logical replication slot can now be implemented application-side for simpler use cases.</p><p><strong>Gotcha</strong>: the special aliases OLD NEW Are added automatically <em>unless your query already defines aliases with those names</em>. If you have a table aliased as OLD NEW In your query, you have to disambiguate manually. Almost no one does this in practice, but it&#39;s worth knowing if you hit a weird parse error.</p><h3>6. OAuth 2.0 Authentication</h3><p>Postgres 18 ships with native OAuth 2.0 authentication support. This is the long-awaited “let me log into Postgres with Okta/Auth0/Azure AD without writing a middleware shim” feature.</p><p>You configure it in pg_hba.conf like any other auth method:</p><pre># pg_hba.conf<br>host    all    all    0.0.0.0/0    oauth    issuer=&quot;https://auth.example.com&quot; scope=&quot;postgres-access&quot;</pre><p>And you load a token validator library via the new oauth_validator_libraries setting:</p><pre># postgresql.conf<br>oauth_validator_libraries = &#39;my_oauth_validator&#39;</pre><p>The validator library is the piece that knows how to verify tokens with your specific identity provider. Postgres ships with the framework but expects the validator to be implemented as an extension — either one your IdP vendor provides, one you write, or one from the community. As of writing, the ecosystem is still maturing here. Cloud-managed Postgres providers (Azure, AWS, GCP) are rolling out validators tied to their respective IdPs.</p><p><strong>Related change</strong>: MD5 password authentication is <strong>now deprecated</strong> and will be removed in Postgres 19. If you still have password_encryption = &#39;md5&#39; anywhere, this is the upgrade where you migrate to scram-sha-256. Check with:</p><pre>SELECT usename, passwd FROM pg_shadow WHERE passwd LIKE &#39;md5%&#39;;</pre><p>If any rows come back, those users have MD5 passwords. Have them reconnect with a new password under SCRAM, then verify with the same query (the prefix will change to SCRAM-SHA-256$).</p><h3>7. Statistics-Preserving pg_upgrade (The Quiet Killer Feature)</h3><p>Anyone who’s done a major-version Postgres upgrade in production knows the dread: the upgrade itself completes in minutes, but the <em>next four hours</em> are agony because all your planner statistics are gone. Every query plan regresses until it ANALYZE finishes. Performance graphs look terrible. On-call gets paged. Customers complain.</p><p>Postgres 18’s pg_upgrade now preserves statistics across the upgrade. No more post-upgrade ANALYZE storm. No more &quot;queries are mysteriously slow for 30 minutes&quot; incidents.</p><p>bash</p><pre># Standard pg_upgrade command — stats now persist automatically<br>pg_upgrade \<br>    --old-bindir=/usr/lib/postgresql/17/bin \<br>    --new-bindir=/usr/lib/postgresql/18/bin \<br>    --old-datadir=/var/lib/postgresql/17/main \<br>    --new-datadir=/var/lib/postgresql/18/main</pre><p>Combined with the new --swap mode (which swaps data directory contents instead of copying or linking, dramatically reducing the upgrade window), this is the smoothest major-version upgrade Postgres has ever shipped.</p><p><strong>Caveat</strong>: extended statistics (CREATE STATISTICS) are preserved structurally but their internal data is not. You&#39;ll want to run ANALYZE on tables that depend heavily on extended stats after the upgrade — but the normal column-level statistics that drive 95% of query plans carry over.</p><h3>8. Temporal Constraints (PERIOD and WITHOUT OVERLAPS)</h3><p>This is the niche feature that, when you need it, you really need it.</p><p>Many business problems involve time ranges that shouldn’t overlap: hotel room bookings, employee scheduling, lease agreements, machine reservations. Modeling this correctly in a relational schema has historically required either heavy application-level validation or clever exclusion constraints with btree_gist.</p><p>Postgres 18 adds first-class temporal constraint syntax:</p><p>sql</p><pre>CREATE TABLE room_bookings (<br>    booking_id  bigserial,<br>    room_id     integer NOT NULL,<br>    period      tstzrange NOT NULL,<br>-- Primary key includes time range<br>    PRIMARY KEY (booking_id, period WITHOUT OVERLAPS),<br>    -- Or: ensure no two bookings for the same room overlap in time<br>    EXCLUDE USING gist (<br>        room_id WITH =,<br>        period WITH &amp;&amp;<br>    )<br>);<br>-- This works<br>INSERT INTO room_bookings (room_id, period) VALUES<br>    (101, tstzrange(&#39;2026-06-10 14:00&#39;, &#39;2026-06-10 16:00&#39;, &#39;[)&#39;));<br>-- This will be rejected with a constraint violation<br>INSERT INTO room_bookings (room_id, period) VALUES<br>    (101, tstzrange(&#39;2026-06-10 15:00&#39;, &#39;2026-06-10 17:00&#39;, &#39;[)&#39;));</pre><p>Foreign keys can now reference temporal primary keys, too, with FOR PORTION OF semantics — if you reference a booking&#39;s time range, the FK ensures your reference stays within the booking&#39;s period. This is part of the SQL:2011 temporal-database spec finally landing in Postgres.</p><p><strong>Who needs this</strong>: anyone modeling reservations, schedules, validity periods, or “history table” patterns. If that’s not you, skip this section.</p><h3>9. Faster NOT NULL Constraints (No Full Table Scan)</h3><p>Adding NOT NULL to a column on a large table used to require a full table scan to verify no nulls existed. On a 500 GB table, this could mean an hour of locks.</p><p>Postgres 18 introduces NOT NULL ... NOT VALID:</p><pre>-- Add the constraint without scanning (fast)<br>ALTER TABLE big_table ADD CONSTRAINT col_not_null NOT NULL col NOT VALID;<br>-- Later, validate at your leisure (still a scan, but doesn&#39;t block writes)<br>ALTER TABLE big_table VALIDATE CONSTRAINT col_not_null;</pre><p>This mirrors the existing CHECK ... NOT VALID pattern but is now first-class for NOT NULL. New rows are enforced immediately; old rows are checked when you run VALIDATE. If validation finds violations, fix them and re-run.</p><p>This is the kind of feature that makes online schema migrations dramatically easier. Tools like pg_repack, pgroll, and Atlas will adopt it within a release or two.</p><h3>10. Self-Join Elimination</h3><p>The planner can now automatically remove some unnecessary self-joins:</p><p>sql</p><pre>-- The query you wrote (or your ORM wrote for you):<br>SELECT u1.name, u1.email<br>FROM users u1<br>JOIN users u2 ON u1.id = u2.id<br>WHERE u1.id = 42;<br><br>-- What PG17 actually executed: two index lookups, one join.<br>-- EXPLAIN output (PG17):<br>--   Nested Loop<br>--     -&gt; Index Scan on users u1  (cost=0.29..8.30)<br>--          Index Cond: (id = 42)<br>--     -&gt; Index Scan on users u2  (cost=0.29..8.30)<br>--          Index Cond: (id = u1.id)<br><br>-- What PG18 actually executes: one index lookup, no join.<br>-- EXPLAIN output (PG18):<br>--   Index Scan on users u1  (cost=0.29..8.30)<br>--     Index Cond: (id = 42)<br><br>-- Equivalent to having written:<br>SELECT name, email FROM users WHERE id = 42;</pre><p>This is the kind of optimization you didn’t know you needed because you assumed your ORM wasn’t writing such queries. It is. They all do, sometimes, especially around polymorphic associations and inheritance mapping. Free perf win, zero code changes.</p><p>You can disable it with SET enable_self_join_elimination = off if it ever causes plan regressions (it shouldn&#39;t, but it&#39;s there).</p><h3>11. Hundreds of Small Wins</h3><p>Beyond the headline features, Postgres 18 ships with the usual long tail of quality-of-life improvements. A non-exhaustive sample:</p><ul><li><strong>Better error messages</strong> — many ERROR lines now include concrete suggestions, not just symptoms.</li><li><strong>B-tree updates</strong> that don’t change indexed columns are noticeably faster (HOT updates work in more cases).</li><li><strong>Foreign key checks</strong> are faster on tables with many FK relationships.</li><li><strong>Large transactions</strong> that modify millions of rows use less memory.</li><li><strong>JSONB query costing</strong> is more accurate, leading to better plans.</li><li><strong>System catalog lock contention</strong> is reduced during schema changes — ALTER TABLE In busy systems, blocks less.</li><li><strong>VACUUM options</strong> expanded: PARALLEL n, INDEX_CLEANUP AUTO, TRUNCATE false, SKIP_LOCKED true — much finer control over how vacuum behaves in production.</li><li><strong>pg_stat_io</strong> gives detailed I/O metrics per backend type and I/O context, finally letting you tune buffer/WAL/temp I/O independently.</li></ul><p>Each of these is a paragraph in the release notes you’d skim past. Together, they make Postgres meaningfully more pleasant to operate.</p><h3>Migration Gotchas (The Bits You’ll Actually Get Bitten By)</h3><p>Now the unglamorous part. PG18 has more breaking changes than recent releases, and most of them will hurt automation scripts before they hurt applications. The big ones:</p><h3>MD5 password authentication is deprecated</h3><p>Already covered, but worth repeating. Any user with an MD5-hashed password will keep working in PG18, but PG19 removes MD5 entirely. Audit and migrate.</p><h3>Time zone abbreviation handling changed</h3><p>Some ambiguous time zone abbreviations now resolve differently. If you store or compare timestamps as strings with abbreviations like EST or CST, double-check. The safer fix is to always use full IANA zone names (America/New_York).</p><h3>VACUUM/ANALYZE inheritance behavior changed</h3><p>VACUUM and ANALYZE on a partitioned-table parent now process child partitions differently — generally more efficiently, but if your monitoring or maintenance scripts parse the output or rely on the old behavior, retest them.</p><h3>COPY FROM end-of-file handling changed</h3><p>Subtle change to how COPY FROM handles trailing whitespace or missing final newlines. If you have ingestion pipelines that produce files programmatically, run them through PG18 in staging before promoting.</p><h3>Generated column default changed</h3><p>Already covered — bare GENERATED ALWAYS AS (...) now means VIRTUAL, not STORED. Always be explicit in DDL.</p><h3>Logical replication of generated columns</h3><p>If you previously relied on the fact that STORED generated columns were <em>not</em> replicated by default, PG18 doesn’t change that default (it’s still publish_generated_columns = none), but the option to enable it now exists. Make sure your downstream consumers can handle the new columns if you turn it on.</p><h3>A Realistic Upgrade Plan</h3><p>Putting it all together, here’s what a sensible team upgrade looks like:</p><ol><li><strong>Read the migration notes section of the release docs.</strong> Yes, all of it. The breaking changes are listed in one place.</li><li><strong>Run PG18 against a copy of production in a staging environment.</strong> Use pg_upgrade --check first to flag obvious problems.</li><li><strong>Test your application’s auth path</strong> — especially if you have MD5 passwords lingering.</li><li><strong>Run your slow-query tests</strong> — skip scan and other planner improvements may surface plans that change. Mostly they get better; occasionally they don’t.</li><li><strong>Plan the upgrade window using </strong><strong>--swap mode</strong> if your downtime budget is tight.</li><li><strong>Don’t enable </strong><strong>io_method = io_uring</strong> in the same maintenance window as the upgrade. Get to PG18 stable first, then change the I/O method on a separate change. One variable at a time.</li><li><strong>Validate </strong><strong>NOT NULL NOT VALID Candidates</strong> — once you&#39;re on PG18, walk through your largest tables and add the deferred constraints you&#39;ve been avoiding.</li></ol><h3>So Should You Upgrade?</h3><p>The honest answer is: yes, but on your schedule, not the marketing team’s.</p><p>PostgreSQL 18 is a substantial release with real wins in performance (async I/O, skip scan), developer ergonomics (UUIDv7, RETURNING OLD/NEW, virtual generated columns), operations (statistics-preserving upgrades, faster constraints), and security (OAuth 2.0, MD5 deprecation). The migration gotchas are real but bounded — none are deal-breakers, and most affect automation scripts rather than application code.</p><p>For most teams, the right upgrade window is 3–6 months after release, by which point the .1 and .2 patch releases have shaken out the rough edges and major cloud providers (RDS, Aurora, Cloud SQL, Azure Database for PostgreSQL) have caught up. Postgres 18.3 shipped on February 26, 2026 — most production-prudent teams are upgrading now.</p><p>The features that will benefit you most depend on your workload:</p><ul><li><strong>OLTP-heavy backend</strong>: UUIDv7, RETURNING OLD/NEW, self-join elimination, faster NOT NULL.</li><li><strong>Analytics or ETL</strong>: Async I/O, vacuum improvements, pg_stat_io.</li><li><strong>Multi-tenant SaaS</strong>: Skip scan, virtual generated columns, OAuth 2.0.</li><li><strong>Operations and SRE</strong>: Statistics-preserving upgrades, --swap mode, NOT NULL NOT VALID.</li><li><strong>Reservations/scheduling apps</strong>: Temporal constraints.</li></ul><p>Pull the Docker image, point a staging copy at it, and start measuring.</p><p>bash</p><pre>docker run --name pg18 -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:18</pre><p>The 30 years of community engineering behind Postgres keep compounding. PG18 isn’t a flashy release. It’s a serious one.</p><p><em>If you’ve already upgraded, I’d love to hear which feature gave you the biggest win — and which gotcha bit you first.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4e07a85a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>