<?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 Charles Sibbald on Medium]]></title>
        <description><![CDATA[Stories by Charles Sibbald on Medium]]></description>
        <link>https://medium.com/@casibbald?source=rss-5e94033d53dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NqDmXSJuE9R4Sn5Q.jpg</url>
            <title>Stories by Charles Sibbald on Medium</title>
            <link>https://medium.com/@casibbald?source=rss-5e94033d53dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:04:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@casibbald/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[The Breach Was Not the Cryptography]]></title>
            <link>https://medium.com/@casibbald/the-breach-was-not-the-cryptography-9df5c6455913?source=rss-5e94033d53dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df5c6455913</guid>
            <category><![CDATA[data-access-governance]]></category>
            <category><![CDATA[encyption]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[web-framework]]></category>
            <dc:creator><![CDATA[Charles Sibbald]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 22:13:10 GMT</pubDate>
            <atom:updated>2026-09-26T22:13:10.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Sep 26, 2026 · Reach me on X @casibbald</p><p><em>Most breaches are not broken cryptography. They are a system use that no one considered. This month’s Revolut disclosures are a clean example, and the fix is the same four ideas whether the reader is a service or a person.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*aqTZb5-96b3GUMQpSwJa8w.png" /></figure><h3>What was reported</h3><p>Two separate incidents reached Revolut customers in September 2026, and neither involved a cracked password or a broken key.</p><p>In the first incident, criminals compromised an Italian government employee’s mailbox with infostealer malware and used that legitimate .gov address to send fraudulent data requests to Revolut Bank UAB in Lithuania. Revolut answered them. The requests ran for roughly five months and covered a reported 680 customers, and the data handed over included “copies of their identity documents including passports and driver’s licenses”, verification selfies, statements and transaction histories. Revolut says its systems and customer funds were unaffected, and nothing suggests passwords were exposed (<a href="https://techcrunch.com/2026/09/12/revolut-confirms-customer-data-breach-through-fake-government-requests/">TechCrunch</a>, <a href="https://www.securityweek.com/revolut-data-breach-5-months-680-high-profile-accounts-3m-ransom/">SecurityWeek</a>).</p><p>The second incident, a US brokerage partner that used to hold Revolut customers’ US-stock accounts, DriveWealth, was social-engineered on 4 and 5 September; names, contact details, employment information and partial account numbers leaked, again with no passwords (<a href="https://www.theregister.com/cyber-crime/2026/09/25/another-week-another-data-breach-for-revolut-customers/5299092">The Register</a>).</p><p>I have no inside knowledge of either company and no view on how their systems are built. What interests me is the shape of the first incident, because it is the shape of most breaches I have seen up close: a request arrived, it looked authorised, it asked for a lot, and the system that answered it had no way to say “that is more than one request should ever return”. That is not a cryptography problem. It is an authorisation problem, and authorisation problems have the same anatomy whether the requester is a service account or a person with a badge.</p><h3>The pattern: an unscoped read path</h3><p>Strip the names away and the first incident is this sequence. I have drawn it from public reporting; the internal steps are my reconstruction of what any such process looks like, not a claim about Revolut’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*M-gS5yzl0xr8PCq64GdobA.png" /></figure><p>Four things are missing from that diagram, and they are missing from most systems that leak.</p><p>There is no proof of identity, only a proof of <em>origin</em>: the request came from a domain that usually sends legitimate requests. A domain is a location, not a person, and locations get stolen.</p><p>There is no scope: the export step returns whatever was asked for. A request for one account and a request for six hundred look the same to the datastore.</p><p>That there is a bulk read path at all: some role can pull identity documents in the clear, in volume, on demand. If that path exists, it will be used, and whoever holds it becomes the target.</p><p>There is no rate or shape signal: the same requester asking for more and more over months failed to raise alerts or concern for a human or a rule to flag.</p><p>Each has a well-understood technical fix, and each fix has a human-process twin. That symmetry is the point of this post.</p><h3>1. Identity is not a domain name</h3><p>In the technical world, we stopped trusting origin years ago. A request to a service carries a signed token; the service fetches the issuer’s public keys and checks the signature, audience, expiry, and subject. Nothing about the IP address, hostname, or sending domain enters into it. In <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a>, Microscaler’s OpenAPI-first Rust router, a route that declares a security: scheme in its spec gets a JWKS bearer provider for free: the handler receives verified claims, or it receives nothing, and there is no way to write a handler that “forgets” to check. The same idea moves the <em>service’s</em> identity out of key files: a pod proves who it is with a projected service-account token exchanged for a short-lived credential, so there is no JSON key to steal from a laptop.</p><p>The human-process twin is dull and effective: a legal request is authenticated by something the requester <em>has</em> and <em>is</em>, not by where the email came from. A signed portal account issued to a named officer, mutual TLS or a hardware key on that account, and an out-of-band callback to the agency’s published switchboard for anything unusual. A stolen mailbox defeats a domain check; it does not defeat a call to a number the attacker does not control.</p><p>What both versions share: the proof is bound to a subject, expires, and can be revoked in one place.</p><h3>2. Every read is scoped to one subject</h3><p>Authentication says who you are. It doesn’t say which rows you may see, and that gap is where data leaks in bulk. Application code that appends WHERE owner_id = $1 to every query is one forgotten clause away from returning everything, and it always gets forgotten eventually, usually in a reporting endpoint or an admin tool.</p><p>Row-level security moves that clause into the database, where a handler cannot omit it. The trick that makes it usable is a session contract: before any statement runs, the connection is told who is asking, transaction-locally, and the policies read that. In <a href="https://github.com/microscaler/lifeguard">Lifeguard</a>, Microscaler’s Postgres connection layer, that is a SessionContext (tenant, subject, organisation, roles) and one call, with_session_transaction, which pins a connection, begins a transaction, runs rls_set_session(…), executes the unit of work and commits. The policies key on sesame_current_subject_id() and friends. A handler that asks for “all credentials” gets the caller’s credentials, because that’s as much as the database will admit exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*Ht4fQxmVDuR7s96blMaX9A.png" /></figure><p>Two details matter more than they look. FORCE ROW LEVEL SECURITY makes the policy apply to the table’s owner too; otherwise, the one role that matters is exempt. And column grants sit beside row policies: a caller can be allowed the <em>metadata</em> of a row and denied the sealed columns, so even the owner of a credential cannot pull its ciphertext through the API.</p><p>The human twin: one request, one account, one ticket. A legal request for six hundred accounts is not a bigger request; it is six hundred requests, each with its own scope, approval, and log line. Volume becomes visible the moment you count it, and 680 over five months is a number that should have set something off.</p><h3>3. A dump is ciphertext</h3><p>Scoping limits what a legitimate caller sees. It does nothing for the attacker who has the database file, the backup, or a shell on a pod that holds credentials in environment variables. That is the common technical breach, and it looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*AOPEwzRy_zUOVS5WJmyYVA.png" /></figure><p>The design that survives this is old and boring, and worth restating because it is so often skipped under time pressure. It is called envelope encryption.</p><p>One root key lives in a key service and never leaves it: in Google Cloud, that is a Cloud KMS key at the HSM protection level (about $1 a month per key version, FIPS 140–2 Level 3, non-exportable); on a self-hosted cluster, it is an OpenBao or Vault transit key. Each user gets their own data key, 32 random bytes, wrapped by the root key and stored beside their rows. Each credential is sealed with AES-256-GCM under the user’s data key, with the user ID and credential ID as additional authenticated data, so a ciphertext copied to another user’s row fails to open. Exactly one service is allowed to ask the key service to unwrap, and it authenticates with its workload identity, not a key file. Nothing else in the system ever sees plaintext; it asks that service to <em>do something with</em> a credential (start this session, send this message) and gets the result. Every unwrap writes a row to an append-only log the service cannot edit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*DpGHNWtbh6G42Hv2XvAoFQ.png" /></figure><p>Three things fall out of this that people underestimate. Cost is flat: one HSM key serves a million users, because it wraps data keys rather than data. Rotation never touches user data: rotate the root key, re-wrap the data keys in a batch, and no credential is decrypted along the way. Deletion becomes instant and provable: delete a user’s wrapped data key, and every credential they ever stored is unrecoverable, backups included.</p><p>The human twin of “a dump is ciphertext” is “the export is not a spreadsheet”. If a legal process must return identity documents, it returns them through a tool that decrypts one record at a time, for one named requester, into a delivery channel with its own audit trail, and never as a bulk file that sits in a mailbox.</p><h3>4. No unaudited break-glass, and be careful what you hand to partners</h3><p>Every system has a moment where someone says, “support needs to see it”. The safest answer is that there is no read path for staff at all: if a user’s stored credential stops working, the user re-enters it, and the only emergency control an operator holds is a kill switch that disables every credential use at once and is reversible in minutes. That trades a little availability for the certainty that a phished operator, a rogue insider or a fake legal request cannot walk out with plaintext, because no route exists to walk out with such data. Any database export of that data would be useless.</p><p>Where a read path must exist, and for regulated data it sometimes must, the rules are the ones any auditor would write: two people to approve, one record per approval, a reason attached, a log the approvers cannot edit, and a rate that a human reviews. The point is not to make the process slow. It is to make the <em>abnormal</em> case visible: one requester, six hundred records, five months.</p><p>The DriveWealth incident is the other half of this. The data that leaked there was data a partner had been given to do a job. Two questions worth asking about every integration: could we have given them a token instead of a credential, and could that token have been scoped to less? A partner holding a per-user OAuth grant that the user can revoke is a very different liability from a partner holding a copy of the customer file. Where a provider offers OAuth, use it even when a password would be quicker to wire up, because the password is a liability you keep and the token is one the user controls.</p><p>The human twin here is the same as the technical one: minimum data, shortest life, revocable in one place, and an inventory of who holds what so the answer to “what did they have?” takes minutes, not weeks.</p><h3>The four layers as they flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*qmyCBflraOmd75GIyiaRNw.png" /></figure><p>A checklist version, for the next design review:</p><p>• Every route and every request path names a verified subject; nothing is trusted because of where it came from.</p><p>• Every read is scoped at the store, not in application code; FORCE row security and column grants, one ticket per record for humans.</p><p>• Secrets and identity documents are ciphertext at rest under a per-subject key wrapped by an HSM-backed root; one service unwraps; nothing is cached in plaintext.</p><p>• No staff read path; a reversible kill switch; where a legal path must exist, dual control and per-record logging.</p><p>• Partners get scoped, revocable tokens, and there is an inventory of what each one holds.</p><p>• Volume is a signal: count requests per requester and alert on shape, not just on failures.</p><h3>The uncomfortable part</h3><p>None of this is new. Envelope encryption is decades old, row-level security shipped in Postgres 9.5, and “verify the requester, not the envelope” is the oldest rule in the book. What is new every year is another breach where a request looked authorised, asked for a lot, and got it. The design work that prevents that is not glamorous, and it does not demo well: it is the conversation where someone asks “what happens if this pod is compromised?” or “what stops one request from returning six hundred accounts?”, and the team decides that the answer “we trust the sender” is not an answer.</p><p>If you build systems that hold other people’s credentials or identity documents, the question for your next design review is not “is it encrypted?”. It is “show me the one place that can read it in the clear, who can call that place, and what the log looks like when they do”. If that takes more than a minute to answer, that is the work.</p><p><em>I am not affiliated with Revolut or DriveWealth. The account of both incidents is taken from public reporting linked above; the internal steps in the first sequence diagram are a generic reconstruction of how such request processes work, not a description of either company’s systems. Lifeguard and BRRTRouter are open-source components from </em><a href="https://github.com/microscaler"><em>Microscaler</em></a><em>, my open-source GitHub organisation.</em></p><p><strong>Sources:</strong> <a href="https://techcrunch.com/2026/09/12/revolut-confirms-customer-data-breach-through-fake-government-requests/">TechCrunch, 12 Sep 2026</a> · <a href="https://www.securityweek.com/revolut-data-breach-5-months-680-high-profile-accounts-3m-ransom/">SecurityWeek</a> · <a href="https://www.theregister.com/cyber-crime/2026/09/25/another-week-another-data-breach-for-revolut-customers/5299092">The Register, 25 Sep 2026</a> · <a href="https://cloud.google.com/kms/pricing">Cloud KMS pricing</a> · <a href="https://www.postgresql.org/docs/current/ddl-rowsecurity.html">PostgreSQL row security policies</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df5c6455913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Lifeguard: A Parallel Universe ORM for Rust Coroutines]]></title>
            <link>https://medium.com/@casibbald/building-lifeguard-a-parallel-universe-orm-for-rust-coroutines-95682da3cfbf?source=rss-5e94033d53dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/95682da3cfbf</guid>
            <category><![CDATA[high-frequency-trading]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[fear-of-failure]]></category>
            <dc:creator><![CDATA[Charles Sibbald]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 07:36:23 GMT</pubDate>
            <atom:updated>2025-12-10T09:40:56.831Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We spent months building a database layer, hit a brick wall, burned it all down, and decided to build an entire ORM from scratch. Because apparently that’s the reasonable thing to do.</em></p><p><strong>Why?</strong> Because we’re building <a href="https://github.com/microscaler/BRRTRouter"><em>BRRTRouter</em></a> — a high-performance API router handling 100,000+ requests per second — and <a href="https://github.com/microscaler/rerp"><em>R</em>ERP</a> — a modular ERP system for enterprises of all sizes. Both need a <strong>blistering fast bridge</strong> to PostgreSQL, the wonder of database systems. And existing ORMs? They don’t work with coroutines. At all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ti4KAlHVfIkVWTFH3zffSA.png" /></figure><h3>The Call to Adventure</h3><p>Let me start with a question that will either make you nod knowingly or scratch your head: <strong>What if I told you that every Rust ORM is fundamentally broken for coroutines?</strong></p><p>Not “suboptimal.” Not “could be better.” <strong>Fundamentally broken.</strong></p><p>I know, I know. That sounds dramatic. But stick with me here, because we’ve spent the better part of a year learning this lesson the hard way, and if I can save you from making the same mistakes, then at least something good came out of our spectacular failure.</p><h3>The Scene: Why We Need This (The Real-World Problem)</h3><p>Let me set the stage properly. This isn’t an academic exercise. We’re building real systems that need real performance.</p><p><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>: The High-Performance API Router</strong></p><p>A few years ago, we started building <a href="https://github.com/microscaler/BRRTRouter"><em>BRRTRouter</em></a><em> — </em>a high-performance API router built on Rust’s may coroutine runtime. If you’re not familiar with coroutines, think of them as lightweight threads that run in user space. They’re fast. They’re predictable. They give you deterministic scheduling and lower memory overhead than traditional async/await.</p><p>The performance numbers were beautiful. We were seeing <strong>85,000–120,000 requests per second</strong> with <strong>p99 latencies under 25ms</strong>. The coroutine model was working exactly as advertised.</p><p>But then we needed database access. And not just any database access — we needed it to be <strong>blistering fast</strong>. Every millisecond matters when you’re handling 100,000 requests per second. A slow database query doesn’t just affect one request — it affects thousands.</p><p><a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a><strong>: The Modular ERP System</strong></p><p>At the same time, we’re building <a href="https://github.com/microscaler/rerp">RERP</a> — a modular ERP system designed for enterprises of all sizes. It’s not a monolithic system, but rather a collection of modules that can be combined to build complete enterprise solutions.</p><p>Think about what an ERP system does:</p><ul><li><strong>Product Management:</strong> Thousands of SKUs, complex pricing rules, and inventory tracking</li><li><strong>Sales &amp; CRM:</strong> Lead management, quotations, orders, invoicing</li><li><strong>Financial Operations:</strong> General ledger, accounts payable/receivable, financial reporting</li><li><strong>Manufacturing:</strong> Bill of materials, production planning, supply chain</li><li><strong>And much more:</strong> HR, project management, eCommerce, POS systems, field service</li></ul><p>Every single one of these modules needs database access. And ERP systems aren’t just CRUD apps; they also handle complex queries, aggregations, reporting, real-time inventory updates, and financial calculations. The database is the <strong>heart</strong> of the system.</p><p><a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a><strong>: Where Scale Takes an Absurd Turn</strong></p><p>But then there’s <a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a>. This is where the scale requirements took an absurd turn. The performance requirements bordered on the absurd.</p><p>We’re talking about: <strong>50,000 concurrent users</strong> hitting the system simultaneously, <strong>Millions of requests per second</strong> across REST and gRPC endpoints. All of this traffic converging on the database like… well, like the Persian Empire converging on Thermopylae</p><p>You know the story: King Leonidas I of Sparta led 300 Spartans (plus allies) against the massive Persian army at Thermopylae. It’s a story of a small, elite force holding off overwhelming numbers through superior tactics and positioning.</p><p>In our case, the “300 Spartans” are the <strong>limited database connections</strong> allowed on cloud databases. Most cloud providers (AWS RDS, Google Cloud SQL, Azure Database) limit you to <strong>100–1200 concurrent connections</strong>. That’s it. That’s your entire army.</p><p>But the incoming traffic? That’s the Persian Empire. <strong>Millions of requests per second</strong> from 50,000+ concurrent users, all requiring database access. REST endpoints. gRPC services. Background jobs. Scheduled tasks. All converging on those precious few database connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*vs9oZgJgKd7ymu_wVi8TcA.png" /></figure><p>This is where connection pooling becomes <strong>critical</strong>. Not just “nice to have.” <strong>Critical.</strong></p><p>If you create a new connection for every request, you’ll exhaust your connection limit in seconds. The database will start rejecting connections. Your service will start failing. The Persian Empire (traffic) will overwhelm your 300 Spartans (connections).</p><p>But with proper connection pooling:</p><ul><li><strong>Persistent connections</strong> that are reused aggressively</li><li><strong>Semaphore-based acquisition</strong> to prevent connection storms</li><li><strong>Health monitoring</strong> to ensure connections stay alive</li><li><strong>Intelligent routing</strong> to maximise connection utilisation</li></ul><p>Your 300 Spartans (connections) can hold the pass (database) against the Persian Empire (traffic).</p><p>This is why Lifeguard’s connection pool design matters. It’s not just about performance, it’s about <strong>survival at scale</strong>. When you have millions of requests per second and only 100–500 database connections, every connection matters. Every millisecond of connection reuse matters. Every optimisation matters.</p><p><a href="https://pricewhisperer.ai/">Pricewhisperer</a> needs a database layer that can:</p><ul><li>Handle millions of requests per second</li><li>Reuse connections aggressively (no connection churn)</li><li>Route queries efficiently (no connection waste)</li><li>Monitor health continuously (no dead connections)</li><li>Scale horizontally (multiple services sharing the connection pool)</li><li><strong>Transparent caching:</strong> Intelligently check Redis first, fall back to the database when needed</li><li><strong>Intelligent read routing:</strong> Read from replicas when healthy, fall back to primary when lagged</li><li><strong>Write routing:</strong> Always write to masters (as PostgreSQL was designed)</li><li><strong>Cache coherence:</strong> LifeReflector ensures Redis stays in sync with database writes</li><li><strong>PostgreSQL-native:</strong> Use PostgreSQL as the gods designed it, replicas for reads, primary for writes</li></ul><p>Lifeguard provides that. A blistering fast bridge to PostgreSQL that makes every connection count. Where 100 connections can handle millions of requests per second through aggressive reuse and intelligent pooling.</p><p><strong>The Transparent Caching System:</strong></p><p>The magic is in the transparency. Your application code doesn’t need to know about Redis. It doesn’t need to know about replicas. It doesn’t need to know about cache coherence. It just calls User::find_by_id(&amp;pool, 42)? and Lifeguard handles the rest:</p><ol><li><strong>Check Redis first:</strong> Is the data cached? If yes, return it (sub-millisecond read)</li><li><strong>Check replica health:</strong> If not cached, is the replica healthy (WAL lag &lt; threshold)? If yes, read from the replica</li><li><strong>Fall back to primary:</strong> If a replica is lagged, read from primary (strong consistency)</li><li><strong>Cache the result:</strong> Store in Redis for future reads (LifeReflector keeps it fresh)</li><li><strong>Writes go to primary:</strong> Always. As PostgreSQL was designed. LifeReflector handles cache invalidation.</li></ol><p>This is how PostgreSQL was meant to be used. Replicas for reads. Primary for writes. Redis for caching. All transparent to your application code. The database layer knows what to do. You write your business logic.</p><p>For <a href="https://pricewhisperer.ai/">Pricewhisperer</a>, this transparency is critical. At millions of requests per second, you can’t afford manual cache management. You can’t afford to think about replica lag. You can’t afford to route queries manually. The system needs to be smart enough to handle it automatically.</p><p>Lifeguard is that system. It uses PostgreSQL as the gods designed it. And it makes it transparent to your code.</p><p>The story of Leonidas at Thermopylae is about a small force using superior tactics to hold off overwhelming numbers. Lifeguard uses a small number of database connections and employs advanced pooling techniques to handle high traffic.</p><p>The 100 men (connections) defeat the Persian Empire (traffic) through superior architecture.</p><p><strong>PostgreSQL: The Wonder of Database Systems</strong></p><p>And we’re building on <strong>PostgreSQL,</strong> the wonder of database systems.</p><p>PostgreSQL isn’t just a database. It’s a complete data platform. It’s the database that powers everything from small startups to Fortune 500 companies. It’s reliable, it’s powerful, and it’s open source. But more than that, it’s <strong>the most advanced open-source database in existence</strong>.</p><p>Here’s why PostgreSQL is the wonder of database systems:</p><p><strong>ACID Compliance &amp; Advanced Features:</strong></p><ul><li>Full ACID compliance with advanced transaction isolation levels</li><li>Serializable snapshot isolation for complex concurrent workloads</li><li>Two-phase commit for distributed transactions</li><li>Point-in-time recovery for data protection</li></ul><p><strong>Data Types &amp; Flexibility:</strong></p><ul><li><strong>JSONB</strong> for flexible document storage (perfect for ERP’s varied data models)</li><li><strong>Arrays</strong> for storing lists directly in the database</li><li><strong>Custom types</strong> for domain-specific data modelling</li><li><strong>Range types</strong> for temporal and numeric ranges</li><li><strong>UUID</strong> for distributed ID generation</li></ul><p><strong>Query Power:</strong></p><ul><li><strong>Full-text search</strong> built in (no external search engine needed)</li><li><strong>Window functions</strong> for analytical queries</li><li><strong>Common Table Expressions (CTEs)</strong> for complex queries</li><li><strong>Recursive queries</strong> for hierarchical data</li><li><strong>Lateral joins</strong> for correlated subqueries</li></ul><p><strong>Data Relationships:</strong></p><ul><li><strong>Foreign keys</strong> with cascading updates/deletes</li><li><strong>Views</strong> for logical data abstraction</li><li><strong>Materialised views</strong> for fast reporting</li><li><strong>Check constraints</strong> for data validation</li><li><strong>Exclusion constraints</strong> for complex uniqueness rules</li></ul><p><strong>Advanced Features:</strong></p><ul><li><strong>PostGIS</strong> for geospatial data (logistics, field service, mapping)</li><li><strong>Partitioning</strong> (RANGE, LIST, HASH) for massive scale</li><li><strong>Replication</strong> (streaming, logical) for high availability</li><li><strong>Triggers</strong> for automated business logic</li><li><strong>Stored procedures</strong> in multiple languages (PL/pgSQL, Python, etc.)</li><li><strong>Extensions</strong> ecosystem (hundreds of extensions available)</li></ul><p><strong>Performance &amp; Scale:</strong></p><ul><li>Handles terabytes of data</li><li>Supports thousands of concurrent connections</li><li>Advanced query planner and optimiser</li><li>Index types: B-tree, Hash, GiST, GIN, BRIN, SP-GiST</li><li>Parallel query execution</li><li>JIT compilation for complex queries</li></ul><p><strong>Reliability:</strong></p><ul><li>Write-ahead logging (WAL) for durability</li><li>Point-in-time recovery</li><li>Hot backups</li><li>Streaming replication</li><li>Logical replication for selective data sync</li></ul><p>PostgreSQL can handle everything from simple CRUD to complex analytical queries. It’s the database that powers:</p><ul><li><strong>GitHub</strong> (millions of repositories)</li><li><strong>Instagram</strong> (billions of photos)</li><li><strong>Uber</strong> (millions of rides)</li><li><strong>Netflix</strong> (streaming infrastructure)</li><li><strong>Apple</strong> (iCloud backend)</li><li><strong>And thousands of other companies</strong></li></ul><p>For <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a>, PostgreSQL provides the reliability and performance we need for authentication, routing rules, and rate limiting.</p><p>For <a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a>, PostgreSQL provides everything an ERP system needs. Complex relationships, JSONB for flexible schemas, materialised views for reporting, full-text search for product catalogues, and the reliability to run a business on.</p><p>PostgreSQL is a leading database system. And it deserves a fast, coroutine-native ORM to access it.</p><p><strong>The Problem: We Need Speed (And Scale)</strong></p><p><a href="https://github.com/microscaler/rerp">RERP</a>, <strong>built on </strong><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>, has a fundamental requirement: a blazing-fast bridge to PostgreSQL</strong>.</p><p>For <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter,</a> every database query adds latency. At 100,000 requests per second, even a 1ms query adds up. We need sub-millisecond database access. We need predictable latency. We need the database layer to be as fast as the router itself.</p><p>For <a href="https://github.com/microscaler/rerp">RERP</a>, the database is the foundation. Every module depends on it. Every operation touches it. Inventory updates need to be instant. Financial calculations need to be fast. Reporting queries need to be completed in seconds, not minutes. The ERP system is only as fast as its database access.</p><p>For <a href="https://pricewhisperer.ai/">Pricewhisperers</a>, the requirements border on the … absurd. <strong>50,000 concurrent users. Millions of requests per second.</strong> All hitting a database with only 100–1200 connections available. This is where connection pooling becomes a matter of survival, not optimisation.</p><p>The cloud database connection limits are like Leonidas’s 300 Spartans. The incoming traffic is like the Persian Empire. You need superior tactics (connection pooling) to win. You need every connection to count. You need aggressive reuse. You need intelligent routing. You need a database layer capable of handling 50concurrent connections per microservice and millions of requests per second.</p><p>This is why we’re building Lifeguard. Not just for performance. For <strong>survival at scale</strong>.</p><p><strong>The Coroutine Advantage</strong></p><p>This is why we chose coroutines.</p><p>Coroutines give us:</p><ul><li><strong>Deterministic scheduling:</strong> We know precisely when queries will run</li><li><strong>Predictable latency:</strong> No future polling overhead</li><li><strong>Lower memory footprint:</strong> Stackful coroutines vs. heap-allocated futures</li><li><strong>Higher throughput:</strong> Cooperative scheduling is more efficient than preemptive</li></ul><p>But here’s the catch! <strong>Every Rust ORM is built for async/await, not coroutines.</strong></p><p>So we had a choice:</p><ol><li>Use async ORMs and lose the coroutine performance benefits</li><li>Write raw SQL and lose type safety, migrations, and all ORM conveniences</li><li>Build our own ORM from scratch</li></ol><p>We chose <strong>option 3</strong>. Because when you need blistering fast database access for systems handling 100,000+ requests per second and enterprise ERP workloads, you don’t compromise on performance.</p><p>But then we needed database access.</p><h3>The Problem: No ORM for Coroutines</h3><p>Here’s the thing about Rust’s database ecosystem: it’s built entirely around async/await. SeaORM? Async. Diesel? Well, it’s async, but complicated. SQLx? Async. Every ORM assumes you’re using Tokio or some other async runtime.</p><p>Coroutines use a fundamentally different concurrency model. They’re not async futures. They’re stackful coroutines that run cooperatively. You can’t just await in a coroutine; there’s no async runtime to await on.</p><p>So we had a choice:</p><ol><li>Write raw SQL (no type safety, no migrations, no abstractions — just pain)</li><li>Use an async ORM (defeats the entire purpose of using coroutines)</li><li>Build something custom (reinvent the wheel, but at least it’s our wheel)</li></ol><p>We chose <strong>option 3.</strong> Because of course we did.</p><p><em>This is the kind of stupid decision you make with mates over too many pints of beer in a pub with Shetland cows as a mascot. You know it’s probably a terrible idea. You know it will take months. You know you’re going to regret it. But in that moment, with the beer flowing and the cows staring at you judgmentally from the walls, it seems like the only reasonable option… ignoring the fact that we still had full-time jobs and families to attend to.</em></p><p><em>“We’ll just build our own ORM,” we said, as if that’s a thing people do. “How hard can it be?”</em></p><p><em>Spoiler: Very hard. Very, very hard. But we didn’t know that yet. We were still in the pub, still drinking, still convinced we were geniuses.</em></p><h3>Why This Matters: The Real-World Impact</h3><p>Before I dive into our spectacular failure, let me explain why this problem matters in concrete terms.</p><p><strong>For services and systems built with </strong><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>:</strong></p><ul><li>Handling 100,000+ requests per second means every microsecond counts</li><li>A 1ms database query adds 1ms to every request</li><li>At scale, that’s 100 seconds of database time per second of wall-clock time</li><li>We need sub-millisecond database access to maintain our performance targets</li><li>Coroutines give us deterministic scheduling; we know precisely when queries run</li><li>But async ORMs add overhead that kills performance</li></ul><p><strong>For </strong><a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a><strong>:</strong></p><ul><li>ERP systems are database-intensive by nature</li><li>Every module depends on fast database access</li><li>Inventory updates need to be instant (warehouse operations depend on it)</li><li>Financial calculations need to be completed in milliseconds (not seconds)</li><li>Reporting queries need to be fast (users won’t wait minutes for reports)</li><li>The entire system is only as fast as its database layer</li></ul><p><strong>The Coroutine Advantage:</strong></p><p>Coroutines offer something that async/await can’t: <strong>deterministic scheduling</strong>. When you spawn a coroutine, you know exactly when it will run. There’s no future polling. No heap allocations for state machines. No context switching overhead. Just clean, predictable execution.</p><p>This is critical for:</p><ul><li><strong>High-throughput systems:</strong> API/Microservices handling 100,000+ RPS per running replica.</li><li><strong>Real-time services:</strong> ERP systems where inventory updates must be instant</li><li><strong>Predictable latency:</strong> Systems where p99 latency matters more than average</li><li><strong>Resource efficiency:</strong> Lower memory footprint means more concurrent operations</li></ul><p><strong>The PostgreSQL Foundation:</strong></p><p>And we’re building on PostgreSQL, the most advanced open-source database It’s not just SQL. It’s:</p><ul><li><strong>JSONB</strong> for flexible document storage (perfect for ERP’s varied data models)</li><li><strong>Full-text search</strong> for product catalogues and knowledge bases</li><li><strong>Materialised views</strong> for fast reporting</li><li><strong>Foreign keys and constraints</strong> for data integrity</li><li><strong>Replication</strong> for high availability</li><li><strong>PostGIS</strong> for logistics, sales territories and field service</li><li><strong>Partitioning</strong> for massive scale</li></ul><p>PostgreSQL can handle everything we need. We need a fast way to talk to it.</p><p><strong>But without a proper ORM, you’re stuck. You either:</strong></p><ul><li>Accept the performance hit of using async ORMs (defeating the purpose of coroutines)</li><li>Write raw SQL and lose all the safety, migrations, and abstractions of an ORM</li><li>Build something custom (which is what we did, and it was… an experience)</li></ul><p>So we set out to build a database layer for coroutines. A blistering fast bridge to PostgreSQL. How hard could it be?</p><p><em>Spoiler: Very hard. Very, very hard.</em></p><h3>The First Attempt (Or: How We Learned That Wrapping Things Doesn’t Always Work)</h3><h3>The Naive Solution</h3><p>Our first thought was, predictably, naive: “We’ll just wrap SeaORM in coroutines!”</p><p>I can hear you groaning. Yes, we know. But hear us out, as it seemed reasonable at the time. SeaORM is a great ORM. It has everything we need: type-safe queries, migrations, relationship handling, the works. We just needed to make it work with coroutines.</p><p>The plan was simple:</p><ol><li>Spawn a may::go! coroutine for each database operation</li><li>Inside each coroutine, spawn a tokio::runtime::current_thread</li><li>Use that runtime to run SeaORM queries</li><li>Use channels to bridge the sync/async boundary</li><li>Profit!</li></ol><p>What could go wrong?</p><h3>Building the Wrapper</h3><p>We started building. The architecture looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*ezl_T8zi0ExV0gxQ3fV6aA.png" /></figure><p><em>The beautiful, terrible bridge we built. Notice all the red? That’s the async runtime we’re trying to avoid.</em></p><p>We created a DbPoolManager that would spawn worker coroutines.</p><p>Each worker would:</p><ul><li>Create its own Tokio runtime</li><li>Connect to the database via SeaORM</li><li>Wait for jobs on a channel</li><li>Execute queries in the Tokio runtime</li><li>Send results back through another channel</li></ul><p>The public API was synchronous (coroutine-friendly), but underneath, we were running async code. It was a bridge. A beautiful, terrible bridge.</p><h3>Initial Success (The Calm Before the Storm)</h3><p>And you know what? It worked. It compiled. It ran. We could query the database. We wrote tests. They passed. We high-fived. We thought we were geniuses.</p><p>“We did it!” we said. “We bridged async and coroutines!”</p><p>Oh, how naive we were.</p><h3>The Cracks Appear</h3><p>The first sign that something was wrong came when we ran benchmarks. The performance was… acceptable. Not great. Not terrible. Just fine.</p><p>However, we used coroutines specifically for performance. “Fine” wasn’t good enough.</p><p>Then we started noticing other issues:</p><p><strong>Memory Overhead:</strong> We were still allocating futures and still using async state machines. The coroutines were helpful, but we were still paying the async tax.</p><p><strong>Complexity:</strong> We were managing two concurrency models. Coroutines for the application layer. Tokio for the database layer. Channels everywhere. It was getting messy.</p><p><strong>Type System Friction:</strong> SeaORM’s types require Send + Sync. Coroutines aren’t Send + Sync (they run on user-space stacks). We had to work around this constantly.</p><p><strong>The Double Indirection:</strong> Every query went: Coroutine → Channel → Tokio Runtime → SeaORM → Database and back. That’s a lot of layers—a lot of overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2AXzZv5nAJAt9QwBBWSpQ.png" /></figure><h3>The Realization</h3><p>After weeks of this, we had a moment of clarity: <strong>We weren’t getting the benefits of coroutines.</strong></p><p>We were using coroutines, yes. But we were still running async code underneath. We were still paying the async tax. We were still dealing with async complexity. We had all the downsides of both approaches and none of the benefits.</p><p>The wrapper wasn’t a solution. It was a band-aid. A very elaborate, very complex band-aid that didn’t actually solve the problem.</p><p>We had built a bridge between two incompatible worlds, and we were the only foolish ones crossing it. And the toll was expensive.</p><h3>Hitting the Brick Wall (Or: Why Async and Coroutines Don’t Mix)</h3><h3>The Fundamental Problem</h3><p>Let me explain why our wrapper approach was doomed from the start. This is important because understanding it will help you avoid the mistakes we made on another misadventure one day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*DFCbhAxVW4YDdZz0wU88ag.png" /></figure><p><strong>Async/await (Tokio, SeaORM):</strong></p><ul><li>Uses heap-allocated futures</li><li>Poll-based scheduling (the runtime polls futures to see if they’re ready)</li><li>Requires Send + Sync bounds (futures can move between threads)</li><li>Context switching via future state machine transitions</li><li>Designed for I/O-bound workloads</li></ul><p><strong>Coroutines (may run-time):</strong></p><ul><li>Uses stackful coroutines (user-space stacks, like threads but lighter)</li><li>Cooperative scheduling (coroutines yield control explicitly)</li><li>Not Send + Sync (coroutines are tied to their stack, can’t move between threads)</li><li>Context switching via stack switching (much faster than future polling)</li><li>Designed for blistering high-throughput, predictable latency</li></ul><p>These are fundamentally incompatible. You can’t just “make async work in coroutines” because:</p><ol><li><strong>Futures need a runtime to poll them.</strong> Coroutines don’t have a polling runtime —they yield cooperatively.</li><li><strong>Async traits require Send + Sync.</strong> Coroutines aren’t Send + Sync because they’re tied to their stack.</li><li><strong>Future polling is overhead.</strong> The whole point of coroutines is to avoid this overhead.</li><li><strong>You can’t await without an async runtime.</strong> Coroutines don’t have one.</li></ol><h3>The SeaORM Dependency Chain</h3><p>SeaORM’s entire architecture assumes async:</p><ul><li>DatabaseConnection is an async trait</li><li>Every query method is an async fn</li><li>The connection pool uses async mutexes</li><li>Transaction management is async</li><li>Even the query builder assumes async execution</li></ul><p>You literally cannot use SeaORM without an async runtime. It’s baked into every layer.</p><h3>Our Attempted Workarounds (A Comedy of Errors)</h3><p>We tried everything. Oh, did we try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*8OzgMqGuOmIxBSQ_ttURWQ.png" /></figure><p>This works, but now we have: — Coroutines spawning async workers — Channels for communication — Double indirection — All the complexity, none of the benefits.</p><p>Every workaround created more problems. We were building a Rube Goldberg machine to query a database.</p><h3>The Hard Truth</h3><p>After months of this, we finally admitted it: <strong>You cannot bridge async and coroutines without significant overhead.</strong></p><p>The architectures are fundamentally incompatible. It’s like trying to put a diesel engine in an electric car. Sure, you can do it, but you lose all the benefits of both.</p><p>Wrapping SeaORM in coroutines is like:</p><ul><li>Putting a Band-Aid on a broken leg</li><li>Using a screwdriver as a hammer</li><li>Trying to fit a square peg in a round hole (and then building an elaborate adapter that makes it work, but badly)</li></ul><p>We had spent months building an elaborate wrapper that didn’t actually solve the problem. We had proven that you <em>can</em> make async ORMs work with coroutines, but you <em>shouldn’t</em>.</p><h3>The Decision Point</h3><p>So we had a choice:</p><ol><li>Continue with the wrapper (accept the overhead, complexity, and lack of benefits)</li><li>Use raw SQL (lose type safety, migrations, and all ORM benefits)</li><li>Start over (build a coroutine-native ORM from scratch)</li></ol><p>We chose <strong>option 3</strong>. Because apparently we’re masochists, but also because it was the only real solution.</p><h3>The Dark Night of the Soul (Or: Months of Mulling Over the Right Approach)</h3><h3>The Pause</h3><p>We stopped coding. We stepped back. We asked ourselves: “What are we actually trying to build?”</p><p>This was important. We had been so focused on making SeaORM work that we lost sight of the goal. We weren’t trying to use SeaORM. We were trying to access a database from coroutines.</p><p>Those are different problems.</p><h3>Exploring Options</h3><p>We spent weeks researching alternatives. Here’s what we found:</p><p><strong>Option 1: Use Raw SQL</strong></p><ul><li>Pros: Works with coroutines, no async overhead</li><li>Cons: No type safety, no migrations, no abstractions, just pain</li><li>Verdict: Not viable for a production system</li></ul><p><strong>Option 2: Build a Minimal Query Builder</strong></p><ul><li>Pros: Lightweight, coroutine-native</li><li>Cons: Still reinventing the wheel, missing ORM features</li><li>Verdict: Better, but incomplete</li></ul><p><strong>Option 3: Fork SeaORM</strong></p><ul><li>Pros: Start with the existing codebase</li><li>Cons: Massive undertaking, maintenance burden, still async underneath</li><li>Verdict: Not a real solution</li></ul><p><strong>Option 4: Build from Scratch</strong></p><ul><li>Pros: Complete control, coroutine-native from the ground up</li><li>Cons: Many months of work, greenfield development</li><li>Verdict: The only real option</li></ul><h3>The Discovery: may_postgres</h3><p>Then we found it: <a href="https://github.com/Xudong-Huang/may_postgres">may_postgres</a>.</p><p>A coroutine-native Postgres client. Ported from rust-postgres specifically for stackful coroutines. No async runtime. No Tokio. Just pure coroutine I/O.</p><p>This was our foundation. This was what we needed, and it had been staring us in the face the whole time. Just sitting there, quietly maintained by Xudong Huang.</p><p>It’s not as popular as rust-postgres (9 stars vs. thousands), but it’s actively maintained, and it’s exactly what we needed: a database client that works natively with coroutines.</p><h3>The “Beg, Borrow, Steal” Strategy</h3><p>With may_postgres as our foundation, we could finally think clearly about what to build and what to borrow.</p><p><strong>What We Can Borrow (Compatible Components):</strong></p><ul><li><strong>SeaQuery</strong> — SQL builder library. It’s runtime-agnostic. It just builds SQL strings. We can use it.</li><li><strong>SeaORM Migration Patterns</strong> — The DSL for migrations. The concepts, not the runtime. We can borrow the patterns.</li><li><strong>Configuration Patterns</strong> — We already have this working.</li><li><strong>Metrics Patterns</strong> — OpenTelemetry integration. Already done.</li></ul><p><strong>What We Must Build (Custom Implementation):</strong></p><ul><li><strong>LifeExecutor</strong> — Trait wrapping may_postgres::Client</li><li><strong>LifeModel</strong> — Immutable database row representation (derive macro)</li><li><strong>LifeRecord</strong> — Mutable insert/update builder (derive macro)</li><li><strong>LifeMigration</strong> — Migration system (borrowing SeaORM patterns, not runtime)</li><li><strong>LifeguardPool</strong> — Connection pool using may_postgres connections</li><li><strong>LifeQuery</strong> — Query builder facade over SeaQuery</li><li><strong>LifeReflector</strong> — Transparent caching layer (Redis + PostgreSQL) coherence system…The money shot!</li></ul><h3>The Vision Takes Shape</h3><p>And that’s when it clicked. We weren’t building a wrapper. We weren’t building a minimal query builder. We were building a <strong>complete ORM</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UgMu9q4OFGF5DoRHH0Tdw.png" /></figure><p>A “parallel universe ORM.” Same functionality as SeaORM, but designed from the ground up for coroutines. No async runtime. No Tokio. Just pure coroutine-native database access.</p><p>It was ambitious. It was “bonkers.” But it was also the only real solution.</p><p>We had spent months trying to make incompatible things work together. We were now going to build something designed correctly from the start.</p><p>The “bonkers” idea became the only viable path.</p><h3>The New Approach (Or: How We’re Actually Going to Build This)</h3><h3>The Architecture</h3><p>So here’s what we’re going to build. The architecture is clean because we’re no longer trying to bridge incompatible systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*UAtLYaWyjGoHJJNvmUqlhg.png" /></figure><p>No Tokio. No async runtime. Just coroutines all the way down.</p><h3>LifeModel &amp; LifeRecord: The ORM Layer</h3><p>The core of our ORM is two abstractions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*LxcXPcTH5J5uNYjYE5aVIQ.png" /></figure><p>The separation is intentional. LifeModel is immutable (safe to pass around). LifeRecord is for mutations (clear intent and type safety).</p><p>We’ll have to build procedural macros to generate all the boilerplate. Just like SeaORM does, but without the async runtime.</p><h3>The Connection Pool: LifeguardPool</h3><p>Here’s where we learned from our mistakes. Our first attempt created connections on demand. That’s expensive (2–50ms per connection). Cloud providers limit connections (200–1200 max). Connection churn becomes a bottleneck.</p><p>But this isn’t just a bottleneck! It’s a <strong>catastrophic failure waiting to happen</strong>. With millions of requests per second and only 100–500 connections available, creating connections on demand means you’ll exhaust your connection limit in seconds. The database will start rejecting connections. Your service will fail.</p><p>So LifeguardPool does it right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*mXkgKHUAgpNxJjVSdBT0Vw.png" /></figure><ul><li><strong>Persistent connections:</strong> Pre-allocated, long-lived Postgres connections (the 300 Spartans)</li><li><strong>Semaphore-based concurrency:</strong> Bounded acquisition prevents connection storms</li><li><strong>Health monitoring:</strong> Automatic detection and reconnection of failed connections</li><li><strong>Aggressive reuse:</strong> Connections are reused, not recreated (every connection counts)</li></ul><p>This is how connection pools should work. We’re not reinventing the wheel here; we’re just making sure the wheel is round. And for this, the difference between handling millions of requests per second and catastrophic failure.</p><p>The 100 connections (Spartans) hold the pass (PostgreSQL) against millions of requests (Persian Empire) through superior tactics (connection pooling).</p><h3>The Migration System: LifeMigration</h3><p>We’re borrowing SeaORM’s migration DSL patterns. The concepts are good. The runtime is the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*VN40eQFjaF4iyrDHrcEvjQ.png" /></figure><p>Same DSL. Same concepts. But synchronous. Coroutine-native. No async runtime.</p><h3>The Killer Feature: LifeReflector</h3><p>This is where it gets interesting. We’re not just building an ORM. We’re building a <strong>distributed cache coherence system</strong>.</p><p><strong>The Problem:</strong> Microservices need caching (Redis) for performance. But maintaining cache consistency across multiple services is notoriously difficult.</p><p>You either:</p><ul><li>Manually invalidate caches (error-prone, complex)</li><li>Use TTL-based expiration (stale data, cache misses)</li><li>Build event-driven invalidation (complex infrastructure)</li></ul><p><strong>But this isn’t just a nice-to-have. It’s a requirement for survival.</strong></p><p>With workload scenarios of <strong>50,000 concurrent users</strong> and <strong>millions of requests per second</strong>, you can’t afford to hit PostgreSQL for every read. You need Redis caching. But with multiple microservices, you need cache coherence.</p><p>Without it:</p><ul><li><strong>Cache stampedes:</strong> Multiple services invalidate the same key simultaneously</li><li><strong>Stale data:</strong> One service updates data, others read stale cached values</li><li><strong>Thundering herd:</strong> Cache miss causes thousands of simultaneous database queries</li><li><strong>Connection exhaustion:</strong> Cache misses overwhelm your 100–1200 connection limit</li></ul><p>At scale, a single cache coherence failure can cascade into a complete system failure. The Persian Empire (traffic) overwhelms the 300 Spartans (connections).</p><p><strong>The Solution: LifeReflector</strong></p><p>A standalone microservice that maintains cluster-wide cache coherence:</p><ul><li><strong>Leader-elected Raft system:</strong> Only one active reflector at a time (no duplicate work)</li><li><strong>Postgres LISTEN/NOTIFY integration:</strong> Subscribes to database change events</li><li><strong>Intelligent cache refresh:</strong> Creates or updates keys in Redis (TTL-based active set)</li><li><strong>Zero-stale reads:</strong> Redis always reflects the current database state</li><li><strong>Horizontal scaling:</strong> All microservices benefit from a single reflector</li><li><strong>Prevents cache stampedes:</strong> Single source of truth for cache invalidation</li><li><strong>Eliminates thundering herd:</strong> Coordinated cache refresh prevents simultaneous queries</li></ul><p><strong>How It Works:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_OWYqNFRscVFiNQhbsECA.png" /></figure><p>1. LifeRecord writes to Postgres → triggers NOTIFY users_changes, ‘{“id”: 42}’</p><p>2. LifeReflector (leader) receives notification</p><p>3. Checks if lifeguard:model:users:42 exists in Redis (active item)</p><p>4. If exists → refreshes from database → updates Redis</p><p>5. If not → ignores (inactive item, TTL expired)</p><p>6. All microservices read from Redis → always fresh data</p><p>This is enterprise-level Coherence-level functionality, but:</p><ul><li>Lighter (no JVM, no enterprise licensing)</li><li>Faster (coroutine-native, no async overhead)</li><li>Simpler (TTL-based active set, no manual invalidation)</li><li>Open source</li></ul><p><strong>Why LifeReflector Matters:</strong></p><p>At <strong>millions of requests per second</strong>, cache coherence isn’t optional. It’s the difference between:</p><ul><li><strong>With LifeReflector:</strong> 99%+ cache hit rate, sub-millisecond reads, 100 connections handle millions of requests</li><li><strong>Without LifeReflector:</strong> Cache stampedes, stale data, thundering herd, connection exhaustion, system failure</li></ul><p>Here’s the math:</p><ul><li><strong>50,000 concurrent users</strong> × <strong>20 requests/second/user</strong> = <strong>1,000,000 requests/second</strong></li><li><strong>Without caching:</strong> 1,000,000 requests/second × 1ms database query = <strong>1,000 seconds of database time per second</strong> (impossible)</li><li><strong>With caching (95% hit rate):</strong> 50,000 cache misses/second × 1ms = <strong>50 seconds of database time per second</strong> (still impossible with 100 connections)</li><li><strong>With LifeReflector (99%+ hit rate):</strong> 10,000 cache misses/second × 1ms = <strong>10 seconds of database time per second</strong> (100 connections can handle ~100 queries/second each = 10,000 total)</li></ul><p>LifeReflector makes the impossible possible. It’s not just cache coherence. It’s <strong>survival at scale</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEfbbE8X5TZ_-PsBvzxy9g.png" /></figure><p>We’re calling it our “killer feature” because it addresses a problem most ORMs don’t even attempt to solve. It’s not just a feature; it’s the architecture that enables extreme scale.</p><p><strong>The </strong><a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a><strong>s Cache Coherence Challenge:</strong></p><p>Imagine this scenario:</p><ol><li><strong>Service A</strong> updates its record (microservice 1 writes to PostgreSQL)</li><li><strong>Service B</strong> reads Service A’s record (microservice 2 reads from Redis — stale data!)</li><li><strong>Service C</strong> reads Service A’s record (microservice 3 reads from Redis — stale data!)</li><li><strong>Service D</strong> reads Service A’s record (microservice 4 reads from Redis — stale data!)</li></ol><p>Without LifeReflector, you have two options:</p><ul><li><strong>Option 1:</strong> Invalidate cache on write (cache stampede — all microservices try to refresh simultaneously)</li><li><strong>Option 2:</strong> Use TTL expiration (stale data for up to TTL duration)</li></ul><p>Both options fail at scale. Cache stampedes exhaust your 100–500 connections. Stale data breaks user experience.</p><p><strong>With LifeReflector:</strong></p><ol><li><strong>User A</strong> updates their profile (microservice 1 writes to PostgreSQL)</li><li><strong>PostgreSQL</strong> sends NOTIFY users_changes, ‘{“id”: 42}’</li><li><strong>LifeReflector</strong> (single leader) receives notification</li><li><strong>LifeReflector</strong> checks if lifeguard:model:users:42 exists in Redis</li><li><strong>LifeReflector</strong> fetches fresh data from PostgreSQL (single query, not thousands)</li><li><strong>LifeReflector</strong> updates Redis with fresh data</li><li><strong>All microservices</strong> read fresh data from Redis (zero database queries)</li></ol><p>One write. One database query for cache refresh. Millions of reads from Redis. The 100 connections (Spartans) defeat the Persian Empire (traffic) through superior cache coherence tactics.</p><p>This is why LifeReflector is critical. It’s not just about performance. It’s about <strong>architectural survival</strong> at an absurd scale.</p><h3>Replica Read Support</h3><p>We’re also building intelligent read routing with WAL lag awareness:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*oNHYyjidVrnr2oxucSUCJA.png" /></figure><p>• <strong>WAL position tracking:</strong> Monitors pg_current_wal_lsn() vs pg_last_wal_replay_lsn()</p><p>• <strong>Dynamic health checks:</strong> Automatically detect replica lag</p><p>• <strong>Intelligent routing:</strong> Routes reads to replicas only when healthy</p><p>• <strong>Automatic fallback:</strong> Falls back to primary if replicas are stale</p><p>• <strong>Strong consistency mode:</strong> Optional causal read-your-writes consistency</p><p>This is interstellar grade stuff. The kind of thing that separates a toy from a real system.</p><h3>Why This Matters (Or: The Impact)</h3><h3>Performance Benefits</h3><p>Let’s talk numbers. We don’t have final benchmarks yet (we’re still building), but based on the architecture:</p><ul><li><strong>2–5× faster than async ORMs</strong> on hot paths (no future polling overhead)</li><li><strong>10×+ faster on minor queries</strong> (no future allocation overhead)</li><li><strong>Predictable p99 latency</strong> (deterministic coroutine scheduling)</li><li><strong>Lower memory footprint</strong> (stackful coroutines vs. heap-allocated futures)</li></ul><p>These aren’t theoretical benefits. These are real performance gains from using the right concurrency model for the job.</p><p><strong>For </strong><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>:</strong></p><ul><li>At 100,000 requests per second, even a 0.1ms improvement matters</li><li>Sub-millisecond database access means we can maintain our p99 &lt; 25ms target</li><li>Lower memory footprint means more concurrent connections</li><li>Predictable latency means consistent performance under load</li></ul><p><strong>For </strong><a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a><strong>:</strong></p><ul><li>Fast database access means instant inventory updates</li><li>Financial calculations are complete in milliseconds, not seconds</li><li>Reporting queries finish quickly (users won’t wait)</li><li>The entire ERP system feels fast and responsive</li></ul><p><strong>For </strong><a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a><strong>:</strong></p><ul><li><strong>50,000 concurrent users</strong> generating millions of requests per second</li><li>Only <strong>100–1200 database connections</strong> available (cloud provider limits)</li><li>Connection pooling is <strong>survival at scale</strong>, not optimisation</li><li>Every connection pool must handle thousands of requests per second</li><li>Aggressive connection reuse is the difference between success and failure</li><li>The 100 connections (Spartans) must defeat the Persian Empire (traffic)</li><li><strong>LifeReflector cache coherence</strong> prevents cache stampedes and thundering herds</li><li><strong>99%+ cache hit rate</strong> means 100 connections can handle millions of requests</li><li><strong>Zero-stale reads</strong> ensure data consistency across all microservices</li><li><strong>TTL-based active set</strong> means only active users consume cache resources</li></ul><p><strong>The PostgreSQL Advantage:</strong></p><ul><li>PostgreSQL is already fast; we just need a fast way to talk to it</li><li>No async overhead means we get closer to raw PostgreSQL performance</li><li>Coroutine-native I/O means we’re not fighting the database</li><li>We’re building a blistering-fast bridge to the wonder of database systems</li><li>Connection pooling and practically magical caching make limited connections handle unlimited scale</li></ul><h3>Architectural Alignment</h3><p>Lifeguard fits perfectly with both <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a> and <a href="https://github.com/microscaler/rerp">RERP</a>. All three use coroutines. All three are designed for high throughput. All three prioritise predictable latency.</p><p><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong> Integration:</strong></p><ul><li>API router handling 100,000+ requests per second</li><li>Needs sub-millisecond database access for authentication, routing, and rate limiting</li><li>Lifeguard provides the fast database bridge it needs</li><li>Unified coroutine model across the entire stack</li></ul><p><a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a><strong> Integration:</strong></p><ul><li>Open-source ERP system with complex database operations</li><li>Needs fast access for inventory, financial, and manufacturing modules</li><li>Lifeguard provides a type-safe ORM with PostgreSQL feature support</li><li>LifeReflector ensures cache coherence across microservices</li><li>Perfect for modular architecture, where each module needs database access</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*YtuKoso0-odSpGkprJtoWA.png" /></figure><p>There’s no async/await boundary. No context switching between concurrency models. Just clean, unified execution.</p><p>This matters. When your entire stack uses the same concurrency model, everything is simpler. Easier to reason about. Easier to debug. Easier to optimise.</p><h3>Unique Features</h3><p>LifeReflector alone is worth the effort. Distributed cache coherence is hard. Most systems don’t even try. We’re building it in.</p><p>Replica read support with WAL lag awareness will relieve the PostgreSQL Master node. Most ORMs don’t handle this. We will.</p><p>Complete PostgreSQL feature support—views, materialised views, JSONB, full-text search, PostGIS, partitioning. We’re building it all.</p><h3>Developer Experience</h3><p>The API is familiar. If you know SeaORM, you’ll feel at home with Lifeguard. But without the async complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*lnNkyeWqFjh2QR-sW5xcSw.png" /></figure><p>Type-safe queries. Compile-time validation. Clear error messages. Complete tooling.</p><p>It’s the ORM experience you want, but built for coroutines.</p><h3>The Ecosystem Impact</h3><p>We’re building the first coroutine-native ORM for Rust. That’s significant.</p><p><strong>For </strong><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>:</strong></p><ul><li>Enables high-performance API routing with database-backed features</li><li>Authentication, rate limiting, and routing rules all need fast database access</li><li>Lifeguard provides the performance foundation <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a> needs</li></ul><p><strong>For </strong><a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a><strong>:</strong></p><ul><li>Enables modular ERP architecture with fast database access</li><li>Each module (CRM, Sales, Inventory, Financial) needs its own database layer</li><li>Lifeguard provides the ORM foundation <a href="https://github.com/microscaler/rerp">RERP</a> needs</li><li>LifeReflector ensures cache coherence across ERP microservices</li></ul><p><strong>For </strong><a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a><strong>:</strong></p><ul><li>Enables extreme scale: 50,000 concurrent users, millions of requests per second</li><li>Connection pooling makes 100–1200 connections handle unlimited traffic</li><li>The 100 connections (Spartans) defeat the Persian Empire (traffic) through superior architecture</li><li>Lifeguard provides the connection efficiency <a href="https://pricewhisperer.ai/">Pricewhisperer</a> needs to survive at scale</li><li><strong>LifeReflector provides cache coherence</strong> that prevents cache stampedes and thundering herds</li><li><strong>99%+ cache hit rate</strong> means Redis handles most reads, PostgreSQL handles only writes and cache misses</li><li><strong>TTL-based active set</strong> means only active users consume cache resources (inactive users’ data expires)</li><li><strong>Zero-stale reads</strong> ensure all microservices see consistent data</li><li>This is where connection pooling and cache coherence become a matter of survival, not optimisation</li></ul><p><strong>For the Ecosystem:</strong></p><ul><li>Enables a new class of high-performance services</li><li>Provides a foundation for coroutine-based tools</li><li>Reference implementation for coroutine-native database access</li><li>Proves that coroutines can be a viable alternative to async/await</li><li>Shows that limited database connections can handle unlimited scale through proper pooling</li></ul><p>If coroutines are going to succeed in Rust, they need proper database access. We’re building that. And we’re building it for systems that need blistering fast access to PostgreSQL, the wonder of database systems. Systems like <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a>, <a href="https://github.com/microscaler/rerp">RERP</a>, or, in the case of <a href="https://pricewhisperer.ai/">Pricewhisperer</a>, where performance and scale requirements are not just necessary, they border on the <strong>absurd</strong>.</p><h3>The Road Ahead (Or: The Plan)</h3><h3>The Phases</h3><p>We’ve broken this down into phases because, let’s be honest, this is a lot of work.</p><p><strong>Phase 1: Foundation (Weeks 1–3)</strong></p><ul><li>Remove SeaORM and Tokio dependencies</li><li>Integrate may_postgres as a database client</li><li>Implement LifeExecutor trait</li><li>Redesign LifeguardPool for may_postgres</li><li>Basic metrics and observability</li></ul><p><strong>Phase 2: ORM Core (Weeks 3–6)</strong></p><ul><li>Build LifeModel derive macro</li><li>Build LifeRecord derive macro</li><li>Implement basic CRUD operations</li><li>Integrate SeaQuery for SQL building</li><li>Type-safe query builders</li></ul><p><strong>Phase 3: Migrations (Weeks 6–8)</strong></p><ul><li>Implement LifeMigration trait</li><li>Build migration runner</li><li>Create CLI tooling (lifeguard migrate)</li><li>Support core PostgreSQL features</li></ul><p><strong>Phase 4: v1 Release (Weeks 8–10)</strong></p><ul><li>Complete PostgreSQL feature support</li><li>TestContainers infrastructure</li><li>Comprehensive documentation</li><li>Integration with <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a></li><li>Performance benchmarks</li></ul><p><strong>Phase 5: Advanced Features (Weeks 10–14)</strong></p><ul><li><strong>LifeReflector (distributed cache coherence)</strong></li><li>Critical for use at scale</li><li>Leader-elected Raft system</li><li>PostgreSQL LISTEN/NOTIFY integration</li><li>Redis cache coherence with TTL-based active set</li><li>Prevents cache stampedes and thundering herds, with millions of requests/second</li><li>Enables 99%+ cache hit rate with zero-stale reads</li><li>Integration testing with early adopters “at scale” requirements</li><li>Redis integration</li><li>Replica read support with WAL lag awareness</li><li>Relation loading</li><li>Materialised views, generated columns</li></ul><p><strong>Phase 6: Enterprise Features (Quarter 3)</strong></p><ul><li>PostGIS support</li><li>Partitioning</li><li>Triggers and stored procedures</li><li>Schema introspection tools</li><li>Code generation from the database, which feeds back into the controller side of <a href="https://github.com/microscaler/BRRTRouter">BRRTRouter</a>.</li></ul><h3>The Challenges</h3><p>Let’s be honest about what we’re up against:</p><ul><li><strong>Greenfield development:</strong> 6–12 months for v1. This is a lot of code.</li><li><strong>Small ecosystem:</strong> May is less popular than Tokio. Less documentation. Fewer examples.</li><li><strong>Maintenance burden:</strong> A complete ORM is a significant ongoing work.</li><li><strong>Risk:</strong> What if May becomes obsolete? What if async Rust wins completely?</li></ul><p>These are real concerns. We’re not ignoring them.</p><h3>Why We’re Doing It Anyway</h3><p>But here’s why we’re doing it anyway:</p><ol><li><strong>The problem is real.</strong> Coroutines need database access. The gap exists.</li><li><strong>The architecture is sound.</strong> We’re not guessing. We know what we’re building.</li><li><strong>The opportunity is unique.</strong> Near-realtime DB access for coroutine-native ORM space.</li><li><strong>The alternative is worse.</strong> Continue with wrappers? Use raw SQL? Neither is viable.</li><li><strong>The vision is compelling.</strong> High-performance, predictable, ORM familiarity.</li></ol><p>We’re not building this because it’s easy. We’re building it because it’s necessary.</p><h3>The Call to Action</h3><p>So here’s where we are: We’ve learned from our mistakes. We’ve found the proper foundation. We have a clear plan.</p><p>We’re building Lifeguard—a complete ORM for Rust coroutines. A parallel universe to SeaORM, but designed correctly from the start.</p><p>If you’re interested, follow along. If you want to contribute, we’d love the help. If you want to use it, it’ll be ready when it’s ready.</p><p>This is a journey. A bonkers, ambitious, probably-foolish journey. But it’s the right journey.</p><h3>Conclusion (Or: The Reflection)</h3><h3>What We Learned</h3><p>We learned a lot from our spectacular failure. Here are the key takeaways:</p><ol><li><strong>You can’t force incompatible architectures together.</strong> Async and coroutines don’t mix. No amount of wrapping will fix that.</li><li><strong>Sometimes you need to start over.</strong> We spent months on a wrapper that didn’t work. Starting over was the right call.</li><li><strong>The “bonkers” idea might be the only viable path.</strong> Building a complete ORM from scratch sounds crazy. But it’s the only real solution.</li><li><strong>Building from scratch is hard, but necessary.</strong> We’re not taking the easy path. We’re taking the right path.</li></ol><h3>The Bigger Picture</h3><p>Rust’s database ecosystem is dominated by async/await. That’s fine. Async/await is excellent for many use cases.</p><p>But coroutines offer something different—deterministic scheduling. Predictable latency. Lower overhead. These matter for high-throughput systems.</p><p>The ecosystem needs diversity. Not everything should be async. Coroutines deserve proper tooling too.</p><p>Lifeguard is that tooling. It’s the ORM that coroutines need. The ORM that shouldn’t exist but does.</p><h3>Final Thoughts</h3><p>We’re building something that shouldn’t need to exist. But it does need to exist, because the gap is real.</p><p><a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a> needs it. <a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a> needs it. <a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a> needs it. Any high-performance system built on coroutines needs it.</p><p>We spent months building a wrapper that didn’t work. We hit a brick wall. We burned it all down.</p><p>And now we’re building an entire ORM from scratch.</p><p>Is it bonkers? Yes. Is it necessary? Also yes.</p><p>This is the journey. The bonkers, ambitious, probably foolish journey of building a parallel universe ORM for Rust coroutines. A blistering fast bridge to PostgreSQL — the wonder of database systems.</p><p>We’re doing this for <a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a> so it can route 100,000+ requests per second with sub-millisecond database latency.</p><p>We’re doing it for <a href="https://github.com/microscaler/rerp"><strong>RERP</strong></a> so that enterprises can run their entire business on a fast, modular ERP system.</p><p>We’re doing it for <a href="https://pricewhisperer.ai/"><strong>Pricewhisperer</strong></a>, where 50,000 concurrent users and millions of requests per second converge on databases with only 100–500 connections available.</p><p>We’re doing it because sometimes the only way forward is to build what doesn’t exist yet.</p><p>And we’re doing it for you! Because you might want to build your next hair-brained idea on <a href="https://github.com/microscaler/BRRTRouter"><strong>BRRTRouter</strong></a><strong>,</strong> the OpenAPI-first framework.</p><p>Because PostgreSQL deserves a fast, coroutine-native ORM. And we’re the ones building it. For systems where scale requirements are not just high, they’re <strong>absurd</strong>.</p><p>The 100 men (connections) defeat the Persian Empire (traffic) through superior architecture.</p><p><em>Follow our journey: </em><a href="https://github.com/microscaler/lifeguard">GitHub</a></p><p><em>Have questions? Found this interesting? Want to contribute? We’d love to hear from you.</em></p><p><strong>About the Author:</strong> Building high-performance systems with Rust coroutines and learning from spectacular failures, and building the tools that should exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95682da3cfbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>