{"id":41937963,"url":"https://github.com/microscaler/lifeguard","last_synced_at":"2026-01-25T18:16:48.638Z","repository":{"id":293916425,"uuid":"984060300","full_name":"microscaler/lifeguard","owner":"microscaler","description":"Lifeguard is a Database connection pool for Postgres built on non blocking coroutines with the ability handle significant query load.","archived":false,"fork":false,"pushed_at":"2026-01-20T19:16:19.000Z","size":4332,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-01-20T19:21:39.329Z","etag":null,"topics":["connection-pooling","otel-configured-true","postgresql","postgresql-database"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microscaler.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-05-15T10:34:55.000Z","updated_at":"2026-01-20T15:31:29.000Z","dependencies_parsed_at":"2025-05-17T23:29:53.724Z","dependency_job_id":null,"html_url":"https://github.com/microscaler/lifeguard","commit_stats":null,"previous_names":["microscaler/lifeguard"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/microscaler/lifeguard","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microscaler%2Flifeguard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microscaler%2Flifeguard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microscaler%2Flifeguard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microscaler%2Flifeguard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microscaler","download_url":"https://codeload.github.com/microscaler/lifeguard/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microscaler%2Flifeguard/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28756433,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-25T16:32:25.380Z","status":"ssl_error","status_checked_at":"2026-01-25T16:32:09.189Z","response_time":113,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["connection-pooling","otel-configured-true","postgresql","postgresql-database"],"created_at":"2026-01-25T18:16:47.873Z","updated_at":"2026-01-25T18:16:48.631Z","avatar_url":"https://github.com/microscaler.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"/docs/images/Lifeguard2.png\" alt=\"Lifeguard logo\" /\u003e\n\u003c/p\u003e\n\n# 🛟 Lifeguard: Coroutine-Driven Database Runtime for Rust\n\n**Lifeguard** is a **complete, production-grade ORM and data access platform** built from the ground up for Rust's `may` coroutine runtime. This is not a wrapper or adapter—it's a **parallel universe ORM** that provides SeaORM-like functionality but is architected natively for coroutines.\n\n---\n\n## 🔥 Why Lifeguard?\n\n**Lifeguard** is a **complete, production-grade ORM and data access platform** built from the ground up for Rust's `may` coroutine runtime. This is not a wrapper or adapter—it's a **parallel universe ORM** that provides SeaORM-like functionality but is architected natively for coroutines.\n\n**The Problem:** Existing Rust ORMs (SeaORM, Diesel, SQLx) are built for async/await and Tokio. The `may` coroutine runtime uses stackful coroutines, not async futures. These are **fundamentally incompatible architectures**—you cannot bridge them without significant performance penalties.\n\n**The Solution:** Build a complete ORM from scratch using `may_postgres` (coroutine-native PostgreSQL client). No async runtime. No Tokio. Pure coroutine I/O.\n\n**Why This Matters:**\n- **BRRTRouter** (the coroutine API framework) needs blistering fast database access for high-throughput applications\n- High-performance microservices need predictable, low-latency database access without async overhead\n- Applications with extreme scale requirements (millions of requests/second) need efficient connection pooling when database connections are limited\n- Coroutines offer deterministic scheduling, lower memory overhead, and predictable latency\n- But without a proper ORM, developers are forced to choose: async ORM (overhead) or raw SQL (no safety)\n\n**Lifeguard solves this** by providing a complete data platform that matches SeaORM's feature set but is built for coroutines, plus **distributed cache coherence** (LifeReflector) that no other ORM provides.\n\n---\n\n## 🚀 What We're Building\n\n### Core ORM: LifeModel \u0026 LifeRecord\n\nA complete ORM system with two primary abstractions:\n\n**LifeModel** (Immutable Database Rows)\n- Represents database rows as immutable Rust structs\n- Generated via `#[derive(LifeModel)]` procedural macro\n- Provides type-safe query builders\n- Automatic row-to-struct mapping\n- Complete SeaORM API parity\n\n**LifeRecord** (Mutable Change Sets)\n- Separate abstraction for inserts and updates\n- Generated via `#[derive(LifeRecord)]` procedural macro\n- Type-safe mutation builders\n- Automatic SQL generation via SeaQuery\n- Change tracking (dirty fields)\n\n```rust\n#[derive(LifeModel)]\n#[table = \"users\"]\nstruct User {\n    #[primary_key]\n    id: i64,\n    email: String,\n    is_active: bool,\n}\n\n#[derive(LifeRecord)]\nstruct NewUser {\n    email: String,\n}\n\n// Usage - no async/await needed!\nlet user = NewUser { email: \"test@example.com\".into() }\n    .insert(\u0026pool)?;\n\nlet found = User::find_by_id(\u0026pool, user.id)?;\nlet users = User::find()\n    .filter(User::Email.eq(\"test@example.com\"))\n    .all(\u0026pool)?;\n```\n\n### Connection Pool: LifeguardPool\n\nA sophisticated connection pool designed for extreme scale:\n\n- **Persistent connections:** Pre-allocated, long-lived Postgres connections (no on-demand creation)\n- **Semaphore-based concurrency:** Bounded acquisition prevents connection storms\n- **Health monitoring:** Automatic detection and reconnection of failed connections\n- **Aggressive reuse:** Every connection handles thousands of requests per second\n- **Coroutine-native:** No async runtime, pure coroutine I/O\n\n**For High-Scale Applications:** When database connections are limited (e.g., 100-500 connections) but traffic is extreme (millions of requests per second), connection pooling becomes critical. LifeguardPool makes a small number of connections (the 300 Spartans) handle massive traffic (the Persian Empire) through aggressive connection reuse and intelligent pooling tactics.\n\n### The Killer Feature: LifeReflector\n\n**Distributed cache coherence system**—this is Lifeguard's unique advantage:\n\nA **standalone microservice** that maintains cluster-wide cache coherence:\n\n- **Leader-elected Raft system:** Only one active reflector at a time (no duplicate work)\n- **Postgres LISTEN/NOTIFY integration:** Subscribes to database change events\n- **Intelligent cache refresh:** Only updates keys that exist in Redis (TTL-based active set)\n- **Zero-stale reads:** Redis always reflects current database state\n- **Horizontal scaling:** All microservices benefit from single reflector\n\n**How It Works:**\n1. LifeRecord writes to Postgres → triggers `NOTIFY`\n2. LifeReflector (leader) receives notification\n3. Checks if key exists in Redis (active item)\n4. If exists → refreshes from database → updates Redis\n5. If not → ignores (inactive item, TTL expired)\n6. All microservices read from Redis → always fresh data\n\n**Result:** Oracle Coherence-level cache consistency with Postgres + Redis, but lighter, faster, and open source.\n\n### Transparent Caching System\n\nLifeguard provides transparent caching that uses PostgreSQL as the gods designed it:\n\n- **Check Redis first:** Sub-millisecond reads if cached\n- **Read from replicas:** When healthy (WAL lag \u003c threshold)\n- **Write to primary:** Always (as PostgreSQL was designed)\n- **LifeReflector keeps cache fresh:** Automatic coherence across microservices\n\nYour application code doesn't need to know about Redis, replicas, or cache coherence. It just calls `User::find_by_id(\u0026pool, 42)?` and Lifeguard handles the rest.\n\n### Replica Read Support\n\nAdvanced read routing with WAL lag awareness:\n\n- **WAL position tracking:** Monitors `pg_current_wal_lsn()` vs `pg_last_wal_replay_lsn()`\n- **Dynamic health checks:** Automatically detects replica lag\n- **Intelligent routing:** Routes reads to replicas only when healthy\n- **Automatic fallback:** Falls back to primary if replicas are stale\n- **Strong consistency mode:** Optional causal read-your-writes consistency\n\n**Read Preference Modes:**\n- `primary` - Always read from primary\n- `replica` - Use replicas when healthy\n- `mixed` - Automatic selection (Redis → replica → primary)\n- `strong` - Causal consistency (wait for replica to catch up)\n\n### Complete Feature Set\n\n**ORM Features (SeaORM Parity):**\n- ✅ Complete CRUD operations\n- ✅ Type-safe query builders\n- ✅ Relations (has_one, has_many, belongs_to, many_to_many)\n- ✅ Migrations (programmatic, data seeding, advanced operations)\n- ✅ Transactions\n- ✅ Raw SQL helpers\n- ✅ Batch operations\n- ✅ Upsert support\n- ✅ Pagination helpers\n- ✅ Entity hooks \u0026 lifecycle events\n- ✅ Validators\n- ✅ Soft deletes\n- ✅ Auto-managed timestamps\n\n**Competitive Features:**\n- ✅ Schema inference (Diesel `table!` macro equivalent)\n- ✅ Session/Unit of Work pattern (SQLAlchemy)\n- ✅ Scopes (ActiveRecord)\n- ✅ Model Managers (Django)\n- ✅ F() Expressions (Django)\n- ✅ Advanced eager loading strategies (SQLAlchemy)\n\n**Unique Features (No Other ORM Has):**\n- ✅ **LifeReflector** - Distributed cache coherence\n- ✅ **Coroutine-native** - No async overhead\n- ✅ **WAL-based replica routing** - Automatic health monitoring\n- ✅ **TTL-based active set** - Adaptive caching\n\n---\n\n## 🏗️ Architecture Overview\n\n### New Architecture (Post-Rebuild)\n\n```mermaid\ngraph TD\n    App[Application Code] --\u003e Pool[LifeguardPool]\n    Pool --\u003e Executor[LifeExecutor]\n    Executor --\u003e may_postgres[may_postgres]\n    may_postgres --\u003e PostgreSQL[PostgreSQL]\n    \n    App --\u003e LifeModel[LifeModel / LifeRecord]\n    LifeModel --\u003e SeaQuery[SeaQuery SQL Builder]\n    SeaQuery --\u003e Executor\n    \n    App --\u003e Redis[Redis Cache]\n    Redis --\u003e LifeReflector[LifeReflector Service]\n    PostgreSQL -- NOTIFY --\u003e LifeReflector\n    LifeReflector --\u003e Redis\n    \n    style App fill:#add8e6,stroke:#333,stroke-width:2px\n    style Pool fill:#90ee90,stroke:#333,stroke-width:2px\n    style Executor fill:#90ee90,stroke:#333,stroke-width:2px\n    style LifeModel fill:#90ee90,stroke:#333,stroke-width:2px\n    style SeaQuery fill:#90ee90,stroke:#333,stroke-width:2px\n    style may_postgres fill:#90ee90,stroke:#333,stroke-width:2px\n    style PostgreSQL fill:#c0c0c0,stroke:#333,stroke-width:2px\n    style Redis fill:#ffcccb,stroke:#333,stroke-width:2px\n    style LifeReflector fill:#add8e6,stroke:#333,stroke-width:2px\n```\n\n**Key Components:**\n- **LifeguardPool**: Persistent connection pool with semaphore-based acquisition\n- **LifeExecutor**: Database execution abstraction over `may_postgres`\n- **LifeModel/LifeRecord**: Complete ORM layer (replaces SeaORM)\n- **SeaQuery**: SQL building (borrowed, compatible with coroutines)\n- **may_postgres**: Coroutine-native PostgreSQL client (foundation)\n- **LifeReflector**: Distributed cache coherence microservice\n- **Redis**: Transparent caching layer\n\n```mermaid\ngraph TD\n    subgraph Frontend[\"Frontend / Clients\"]\n        Web[Web App]\n        Mobile[Mobile App]\n        API[API Clients]\n    end\n    \n    subgraph BFF[\"BFF Layer\u003cbr/\u003eBuilt with BRRTRouter\"]\n        BFF_Service[Backend for Frontend\u003cbr/\u003eAPI Gateway / Router]\n    end\n    \n    subgraph Backend[\"Backend Microservices\u003cbr/\u003eYour Business Logic\"]\n        MS1[User Service]\n        MS2[Product Service]\n        MS3[Order Service]\n        MSN[Service N\u003cbr/\u003eYour Domain]\n    end\n    \n    subgraph Lifeguard\n        Pool[LifeguardPool]\n        Executor[LifeExecutor]\n        LifeModel[LifeModel / LifeRecord]\n        SeaQuery[SeaQuery]\n    end\n    \n    subgraph Data Layer\n        may_postgres[may_postgres]\n        PostgreSQL[(PostgreSQL)]\n        Redis[(Redis Cache)]\n    end\n    \n    subgraph LifeReflector\n        Reflector[LifeReflector Leader]\n    end\n    \n    Web --\u003e BFF_Service\n    Mobile --\u003e BFF_Service\n    API --\u003e BFF_Service\n    \n    BFF_Service --\u003e MS1\n    BFF_Service --\u003e MS2\n    BFF_Service --\u003e MS3\n    BFF_Service --\u003e MSN\n    \n    MS1 --\u003e Pool\n    MS2 --\u003e Pool\n    MS3 --\u003e Pool\n    MSN --\u003e Pool\n    \n    Pool --\u003e Executor\n    Executor --\u003e LifeModel\n    LifeModel --\u003e SeaQuery\n    SeaQuery --\u003e Executor\n    Executor --\u003e may_postgres\n    may_postgres --\u003e PostgreSQL\n    \n    MS1 --\u003e Redis\n    MS2 --\u003e Redis\n    MS3 --\u003e Redis\n    MSN --\u003e Redis\n    PostgreSQL -- NOTIFY --\u003e Reflector\n    Reflector --\u003e Redis\n    \n    style Frontend fill:#e1f5ff\n    style Web fill:#e1f5ff\n    style Mobile fill:#e1f5ff\n    style API fill:#e1f5ff\n    style BFF fill:#add8e6\n    style BFF_Service fill:#add8e6\n    style Backend fill:#d4edda\n    style MS1 fill:#d4edda\n    style MS2 fill:#d4edda\n    style MS3 fill:#d4edda\n    style MSN fill:#d4edda\n    style Pool fill:#90ee90\n    style Executor fill:#90ee90\n    style LifeModel fill:#90ee90\n    style may_postgres fill:#90ee90\n    style PostgreSQL fill:#c0c0c0\n    style Redis fill:#ffcccb\n    style Reflector fill:#add8e6\n```\n\n### Connection Pool Architecture\n\n```mermaid\ngraph TD\n    subgraph LifeguardPool[\"LifeguardPool\u003cbr/\u003eThe 300 Spartans\"]\n        S[Semaphore\u003cbr/\u003emax_connections tokens\u003cbr/\u003e100-500 limit]\n        subgraph Slots[\"Connection Slots\u003cbr/\u003ePersistent \u0026 Reused\"]\n            C1[Slot 1\u003cbr/\u003ein_use: false\u003cbr/\u003eready]\n            C2[Slot 2\u003cbr/\u003ein_use: true\u003cbr/\u003eexecuting query]\n            C3[Slot 3\u003cbr/\u003ein_use: false\u003cbr/\u003eready]\n            CN[Slot N\u003cbr/\u003ein_use: false\u003cbr/\u003eready]\n        end\n    end\n    \n    subgraph Traffic[\"Incoming Traffic\u003cbr/\u003eThe Persian Empire\"]\n        R1[Request 1]\n        R2[Request 2]\n        R3[Request 3]\n        RN[Request N\u003cbr/\u003emillions/sec]\n    end\n    \n    Traffic --\u003e|acquire| S\n    S --\u003e|find free| Slots\n    Slots --\u003e|mark in_use| C2\n    C2 --\u003e|execute query| PG[PostgreSQL\u003cbr/\u003eThe Pass]\n    PG --\u003e|result| C2\n    C2 --\u003e|release| S\n    C2 --\u003e|mark free| Slots\n    C2 --\u003e|ready for| Traffic\n    \n    style LifeguardPool fill:#fff4e1\n    style S fill:#fff4e1\n    style Slots fill:#e1ffe1\n    style PG fill:#e1ffe1\n    style Traffic fill:#ffe1e1\n    \n    Note[100 connections\u003cbr/\u003ehandle millions of requests\u003cbr/\u003ethrough aggressive reuse]\n    LifeguardPool --\u003e Note\n```\n\n### LifeReflector Cache Coherence\n\n```mermaid\nsequenceDiagram\n    participant LifeRecord\n    participant Postgres\n    participant LifeReflector\n    participant Redis\n    participant LifeModel\n\n    LifeRecord-\u003e\u003ePostgres: Write (INSERT/UPDATE/DELETE)\n    Postgres-\u003e\u003ePostgres: Commit Transaction\n    Postgres-\u003e\u003eLifeReflector: NOTIFY table_changes, '{\"id\": 42}'\n    LifeReflector-\u003e\u003eRedis: EXISTS lifeguard:model:table:42?\n    alt Key Exists (Active Item)\n        LifeReflector-\u003e\u003ePostgres: SELECT * FROM table WHERE id = 42 (from Primary)\n        Postgres--\u003e\u003eLifeReflector: Fresh Data\n        LifeReflector-\u003e\u003eRedis: SETEX lifeguard:model:table:42 \u003cTTL\u003e \u003cSerialized Data\u003e\n    else Key Not Exists (Inactive)\n        LifeReflector-\u003e\u003eLifeReflector: Ignore (item not cached, TTL expired)\n    end\n    LifeModel-\u003e\u003eRedis: Read (GET lifeguard:model:table:42)\n    alt Cache Hit\n        Redis--\u003e\u003eLifeModel: Cached Data (Fresh)\n    else Cache Miss\n        LifeModel-\u003e\u003ePostgres: Read (SELECT * FROM table WHERE id = 42)\n        Postgres--\u003e\u003eLifeModel: Data\n        LifeModel-\u003e\u003eRedis: SETEX lifeguard:model:table:42 \u003cTTL\u003e \u003cSerialized Data\u003e\n    end\n```\n\n\n\n\n\n---\n\n## 💻 Getting Started\n\n**Note:** Lifeguard is currently being rebuilt from scratch. The following examples show the target API (not yet implemented).\n\n### Installation\n\n```toml\n[dependencies]\nlifeguard = { git = \"https://github.com/microscaler/lifeguard\" }\n```\n\n### Basic Usage\n\n```rust\nuse lifeguard::*;\n\n// Create connection pool\nlet pool = LifeguardPool::new(\"postgresql://user:pass@localhost/dbname\")?;\n\n// Define model\n#[derive(LifeModel)]\n#[table = \"users\"]\nstruct User {\n    #[primary_key]\n    id: i64,\n    email: String,\n    is_active: bool,\n}\n\n// Query (no async/await needed!)\nlet user = User::find_by_id(\u0026pool, 1)?;\nlet users = User::find()\n    .filter(User::Email.eq(\"test@example.com\"))\n    .all(\u0026pool)?;\n\n// Insert\n#[derive(LifeRecord)]\nstruct NewUser {\n    email: String,\n}\n\nlet user = NewUser { email: \"test@example.com\".into() }\n    .insert(\u0026pool)?;\n```\n\n### With Caching (Transparent)\n\n```rust\n// Caching is transparent - no code changes needed!\n// Lifeguard automatically:\n// 1. Checks Redis first\n// 2. Falls back to database if cache miss\n// 3. Caches result for future reads\n// 4. LifeReflector keeps cache fresh\n\nlet user = User::find_by_id(\u0026pool, 1)?; // May come from Redis or DB\n```\n\n### With Replicas (Automatic Health Monitoring)\n\n```rust\n// Configure read preferences\nlet pool = LifeguardPool::new(url)?\n    .with_read_preference(ReadPreference::Mixed); // Redis → replica → primary\n\n// Lifeguard automatically:\n// 1. Checks Redis first\n// 2. Routes to healthy replicas\n// 3. Falls back to primary if replicas lagged\n// 4. Monitors WAL lag continuously\n\nlet users = User::find().all(\u0026pool)?; // Automatically routed\n```\n\n\n---\n\n## 📊 Observability\n\nComprehensive instrumentation for production operations:\n\n### Prometheus Metrics\n\n- `lifeguard_pool_size` - Current pool size\n- `lifeguard_active_connections` - Active connections\n- `lifeguard_connection_wait_time` - Time waiting for connection\n- `lifeguard_query_duration_seconds` - Query execution time\n- `lifeguard_query_errors_total` - Query errors\n- `lifeguard_cache_hits_total` - Cache hits\n- `lifeguard_cache_misses_total` - Cache misses\n- `lifeguard_replica_lag_bytes` - Replica lag (bytes)\n- `lifeguard_replica_lag_seconds` - Replica lag (seconds)\n- `lifeguard_replicas_healthy` - Number of healthy replicas\n\n### OpenTelemetry Tracing\n\n- Distributed tracing for database operations\n- Spans for: connection acquisition, query execution, cache operations\n- Integration with existing OpenTelemetry infrastructure\n\n### LifeReflector Metrics\n\n- `reflector_notifications_total` - Notifications received\n- `reflector_refreshes_total` - Cache refreshes\n- `reflector_ignored_total` - Ignored notifications (inactive items)\n- `reflector_active_keys` - Active cache keys\n- `reflector_redis_latency_seconds` - Redis operation latency\n- `reflector_pg_latency_seconds` - PostgreSQL operation latency\n- `reflector_leader_changes_total` - Leader election events\n\n---\n\n## 🧪 Testing\n\nLifeguard includes a comprehensive testkit for testing database operations:\n\n```rust\nuse lifeguard::testkit::*;\n\n#[test]\nfn test_user_operations() {\n    let pool = test_pool!();\n    \n    let user = NewUser { email: \"test@example.com\".into() }\n        .insert(\u0026pool)?;\n    \n    assert_eq!(user.email, \"test@example.com\");\n}\n```\n\nThe testkit provides:\n- Test database setup/teardown\n- Transaction rollback after each test (clean state)\n- Fixture loading helpers\n- Test database isolation\n\n---\n\n## 🗺️ Roadmap\n\n### Epic 01: Foundation (Weeks 1-3)\n- ✅ Remove SeaORM and Tokio dependencies\n- ✅ Integrate `may_postgres` as database client\n- ✅ Implement `LifeExecutor` trait\n- ✅ Redesign `LifeguardPool` for `may_postgres`\n- ✅ Basic metrics and observability\n- ✅ Transaction support\n- ✅ Raw SQL helpers\n\n### Epic 02: ORM Core (Weeks 3-6)\n- ✅ Build `LifeModel` derive macro\n- ✅ Build `LifeRecord` derive macro\n- ✅ Implement basic CRUD operations\n- ✅ Integrate SeaQuery for SQL building\n- ✅ Type-safe query builders\n- ✅ Batch operations\n- ✅ Upsert support\n- ✅ Pagination helpers\n- ✅ Entity hooks \u0026 lifecycle events\n- ✅ Validators\n- ✅ Soft deletes\n- ✅ Auto-managed timestamps\n- ✅ Session/Unit of Work pattern\n- ✅ Scopes\n- ✅ Model Managers\n- ✅ F() Expressions\n\n### Epic 03: Migrations (Weeks 6-8)\n- ✅ Implement `LifeMigration` trait\n- ✅ Build migration runner\n- ✅ Create CLI tooling (`lifeguard migrate`)\n- ✅ Support core PostgreSQL features\n- ✅ Programmatic migrations and data seeding\n- ✅ Advanced migration operations\n\n### Epic 04: v1 Release (Weeks 8-10)\n- ✅ Complete PostgreSQL feature support\n- ✅ Testkit infrastructure\n- ✅ Comprehensive documentation\n- ✅ Integration with BRRTRouter\n- ✅ Performance benchmarks\n\n### Epic 05: Advanced Features (Weeks 10-14)\n- ✅ LifeReflector (distributed cache coherence)\n- ✅ Redis integration\n- ✅ Replica read support with WAL lag awareness\n- ✅ Complete relation support\n- ✅ Materialized views\n- ✅ Query cache support\n- ✅ Cache statistics \u0026 monitoring\n\n### Epic 06: Enterprise Features (Weeks 15 - 20)\n- ✅ PostGIS support\n- ✅ Partitioning\n- ✅ Triggers and stored procedures\n- ✅ Schema introspection tools (Diesel `table!` equivalent)\n- ✅ Code generation from database\n- ✅ Schema-first design\n\nSee [EPICS](./docs/EPICS/) for detailed stories and progress tracking.\n\n---\n\n## 🎯 Competitive Metrics: Lifeguard vs Rust ORMs\n\n*Implementation status based on current codebase analysis (see `lifeguard-derive/SEAORM_LIFEGUARD_MAPPING.md`)*\n\n| Feature | Lifeguard Promise | Implementation Status | SeaORM | Diesel | SQLx |\n|---------|-------------------|----------------------|--------|--------|------|\n| **Concurrency Model** | ✅ Coroutine-native (`may`) | ✅ **Implemented** | ❌ Async/await (Tokio) | ❌ Sync-only | ❌ Async/await (Tokio) |\n| **Performance (Hot Paths)** | ✅✅✅ 2-5× faster | 🟡 **Architectural** | ⚠️ Async overhead | ✅ Fast (sync) | ⚠️ Async overhead |\n| **Performance (Small Queries)** | ✅✅✅ 10×+ faster | 🟡 **Architectural** | ⚠️ Future allocation | ✅ Fast | ⚠️ Future allocation |\n| **Memory Footprint** | ✅✅ Low (stackful coroutines) | 🟡 **Architectural** | ⚠️ Higher (heap futures) | ✅ Low | ⚠️ Higher (heap futures) |\n| **Predictable Latency** | ✅✅✅ Deterministic scheduling | 🟡 **Architectural** | ⚠️ Poll-based (variable) | ✅ Predictable | ⚠️ Poll-based (variable) |\n| **Type Safety** | ✅✅✅ Compile-time validation | ✅ **Implemented** | ✅✅ Compile-time validation | ✅✅✅ Strong compile-time | ✅✅ Compile-time SQL checks |\n| **ORM Features** | ✅✅✅ Complete (SeaORM parity) | 🟡 **67% Complete** (Core traits, relations, query builder) | ✅✅✅ Complete | ✅✅ Good | ❌ Query builder only |\n| **CRUD Operations** | ✅✅✅ Full support | ✅ **Implemented** (insert/update/save/delete via ActiveModelTrait) | ✅✅✅ Full support | ✅✅ Full support | ⚠️ Manual SQL |\n| **Relations** | ✅✅✅ All types (has_one, has_many, belongs_to, many_to_many) | ✅ **Implemented** (Complete with eager/lazy loading, composite keys, DeriveLinked) | ✅✅✅ All types | ✅✅ Basic support | ❌ Manual joins |\n| **Migrations** | ✅✅✅ Programmatic, data seeding, advanced ops | 🟡 **Partial** (DeriveMigrationName missing, infrastructure may exist) | ✅✅✅ Programmatic | ✅✅ CLI-based | ⚠️ Manual SQL |\n| **Schema Inference** | ✅✅✅ From database (Diesel equivalent) | ❌ **Not Implemented** | ✅✅ From database | ✅✅✅ `table!` macro | ❌ No |\n| **Query Builder** | ✅✅✅ Type-safe, chainable | ✅ **Implemented** (19/20 methods, 95% coverage) | ✅✅✅ Type-safe, chainable | ✅✅✅ Compile-time checked | ✅✅ Compile-time SQL |\n| **Transactions** | ✅✅✅ Full support | ✅ **Implemented** (Roadmap Epic 01) | ✅✅✅ Full support | ✅✅ Full support | ✅✅ Full support |\n| **Batch Operations** | ✅✅✅ insert_many, update_many, delete_many | ✅ **Implemented** | ✅✅✅ Batch support | ✅✅ Batch support | ⚠️ Manual |\n| **Upsert** | ✅✅✅ save(), on_conflict() | ✅ **Implemented** (save() method exists) | ✅✅✅ save(), on_conflict() | ✅✅ on_conflict() | ⚠️ Manual SQL |\n| **Pagination** | ✅✅✅ paginate(), paginate_and_count() | ✅ **Implemented** | ✅✅✅ Pagination helpers | ⚠️ Manual | ⚠️ Manual |\n| **Entity Hooks** | ✅✅✅ before/after lifecycle events | ✅ **Implemented** (ActiveModelBehavior with 8 lifecycle hooks) | ✅✅✅ Hooks support | ❌ No | ❌ No |\n| **Validators** | ✅✅✅ Field \u0026 model-level | ❌ **Not Implemented** | ⚠️ Limited | ❌ No | ❌ No |\n| **Soft Deletes** | ✅✅✅ Built-in support | ❌ **Not Implemented** | ⚠️ Manual | ❌ No | ❌ No |\n| **Auto Timestamps** | ✅✅✅ created_at, updated_at | ❌ **Not Implemented** | ⚠️ Manual | ❌ No | ❌ No |\n| **Session/Unit of Work** | ✅✅✅ Identity map, dirty tracking | ❌ **Not Implemented** | ❌ No | ❌ No | ❌ No |\n| **Scopes** | ✅✅✅ Named query scopes | ❌ **Not Implemented** | ❌ No | ❌ No | ❌ No |\n| **Model Managers** | ✅✅✅ Custom query methods | ✅ **Implemented** (ModelManager trait + custom methods pattern) | ❌ No | ❌ No | ❌ No |\n| **F() Expressions** | ✅✅✅ Database-level expressions | ❌ **Not Implemented** | ❌ No | ⚠️ Limited | ❌ No |\n| **Subqueries** | ✅✅✅ Full support | 🟡 **Future** (Not yet implemented) | ✅✅✅ Full support | ✅✅ Full support | ✅✅ Manual SQL |\n| **CTEs** | ✅✅✅ WITH clauses | 🟡 **Future** (Not yet implemented) | ✅✅✅ WITH clauses | ✅✅ WITH clauses | ✅✅ Manual SQL |\n| **Window Functions** | ✅✅✅ Full support | 🟡 **Future** (Not yet implemented) | ✅✅✅ Full support | ✅✅ Full support | ✅✅ Manual SQL |\n| **Eager Loading** | ✅✅✅ Multiple strategies (joinedload, subqueryload, selectinload) | ✅ **Implemented** (selectinload strategy with FK extraction) | ✅✅✅ Eager loading | ⚠️ Manual | ❌ Manual |\n| **Raw SQL** | ✅✅✅ find_by_statement(), execute_unprepared() | ✅ **Implemented** (Architecture supports raw SQL) | ✅✅✅ Raw SQL support | ✅✅✅ Raw SQL support | ✅✅✅ Primary feature |\n| **Connection Pooling** | ✅✅✅ Persistent, semaphore-based, health monitoring | ✅ **Implemented** (LifeguardPool architecture) | ✅✅✅ Built-in pool | ⚠️ External (r2d2) | ✅✅✅ Built-in pool |\n| **Replica Read Support** | ✅✅✅ WAL-based health monitoring, automatic routing | 🟡 **Architectural** (Not in SeaORM mapping, may exist) | ❌ No | ❌ No | ❌ No |\n| **Read Preferences** | ✅✅✅ primary, replica, mixed, strong | 🟡 **Architectural** (Not in SeaORM mapping, may exist) | ❌ No | ❌ No | ❌ No |\n| **Distributed Caching** | ✅✅✅✅ **LifeReflector (UNIQUE)** | 🟡 **Architectural** (Not in SeaORM mapping, may exist) | ❌ No | ❌ No | ❌ No |\n| **Cache Coherence** | ✅✅✅✅ **Zero-stale reads (UNIQUE)** | 🟡 **Architectural** (Not in SeaORM mapping, may exist) | ❌ No | ❌ No | ❌ No |\n| **TTL-Based Active Set** | ✅✅✅✅ **Adaptive caching (UNIQUE)** | 🟡 **Architectural** (Not in SeaORM mapping, may exist) | ❌ No | ❌ No | ❌ No |\n| **PostgreSQL Features** | ✅✅✅ Views, materialized views, JSONB, FTS, PostGIS, partitioning | 🟡 **Partial** (JSONB ✅ core feature, others future) | ✅✅✅ Most features | ✅✅✅ Most features | ✅✅✅ All features (raw SQL) |\n| **Observability** | ✅✅✅ Prometheus, OpenTelemetry, comprehensive metrics | 🟡 **Partial** (Metrics infrastructure exists) | ✅✅ Basic metrics | ⚠️ Limited | ⚠️ Limited |\n| **Developer Experience** | ✅✅✅ Familiar API, no async/await, clear errors | ✅ **Implemented** (SeaORM-like API) | ✅✅✅ Good, async/await required | ⚠️ Complex type system | ✅✅ Good, async/await required |\n| **Learning Curve** | ✅✅ Moderate (familiar if you know SeaORM) | ✅ **Implemented** (SeaORM-like API) | ✅✅ Moderate | ⚠️ Steep (complex macros) | ✅✅ Moderate |\n| **Production Ready** | ✅✅✅ Complete observability, health checks, metrics | 🟡 **Partial** (Core ORM ready, advanced features pending) | ✅✅✅ Production ready | ✅✅✅ Production ready | ✅✅✅ Production ready |\n| **Multi-Database** | ❌ PostgreSQL only (by design) | ✅ **By Design** | ✅✅ PostgreSQL, MySQL, SQLite | ✅✅ PostgreSQL, MySQL, SQLite | ✅✅✅ PostgreSQL, MySQL, SQLite, MSSQL |\n| **Coroutine Runtime** | ✅✅✅✅ **Native support (UNIQUE)** | ✅ **Implemented** | ❌ Incompatible | ❌ Incompatible | ❌ Incompatible |\n\n### Legend\n\n**Implementation Status Column:**\n- ✅ **Implemented** = Feature is fully implemented and working\n- 🟡 **Partial/Future/Architectural** = Partially implemented, planned for future, or architectural feature (not in SeaORM mapping)\n- ❌ **Not Implemented** = Feature promised but not yet implemented\n\n**Feature Comparison Columns:**\n- ✅✅✅✅ = **Unique advantage** (no other ORM has this)\n- ✅✅✅ = Excellent support\n- ✅✅ = Good support\n- ✅ = Basic support\n- ⚠️ = Limited or manual implementation required\n- ❌ = Not supported\n\n### Implementation Status Summary\n\n**✅ Fully Implemented (Core ORM - 67% of SeaORM parity):**\n- Core traits (LifeModelTrait, ModelTrait, ActiveModelTrait, ColumnTrait, PrimaryKeyTrait)\n- Complete CRUD operations (insert, update, save, delete)\n- Relations system (has_one, has_many, belongs_to, has_many_through) with composite key support\n- Query builder (19/20 methods, 95% coverage)\n- Eager/lazy loading with multiple strategies\n- Pagination, batch operations, upsert\n- Entity hooks (ActiveModelBehavior with 8 lifecycle hooks)\n- JSON support (core feature, always enabled)\n- Partial models (DerivePartialModel)\n- Multi-hop relationships (DeriveLinked - competitive advantage)\n\n**🟡 Partially Implemented / Future:**\n- Migrations (infrastructure may exist, but DeriveMigrationName macro missing)\n- Subqueries, CTEs, Window Functions (planned for future)\n- PostgreSQL advanced features (JSONB ✅, others future)\n- Observability (metrics infrastructure exists, full implementation pending)\n\n**❌ Not Yet Implemented (Promised but Missing):**\n- Validators (field \u0026 model-level)\n- Soft deletes\n- Auto-managed timestamps\n- Session/Unit of Work pattern\n- Scopes (named query scopes)\n- Model Managers (custom query methods)\n- F() Expressions (database-level expressions)\n- Schema inference (Diesel `table!` equivalent)\n\n**🟡 Architectural Features (Not in SeaORM mapping, status unclear):**\n- LifeReflector (distributed cache coherence)\n- Replica read support with WAL-based routing\n- Read preferences (primary, replica, mixed, strong)\n- TTL-based active set caching\n\n**Overall Progress:** ~67% of SeaORM feature parity achieved. Core ORM functionality is complete and production-ready. Advanced features (validators, soft deletes, scopes) and architectural features (LifeReflector, replica routing) are pending.\n\n### Key Differentiators\n\n**Lifeguard's Unique Advantages:**\n1. **LifeReflector** - Distributed cache coherence (Oracle Coherence-level) - **NO OTHER ORM HAS THIS** (🟡 Status unclear)\n2. **Coroutine-Native** - No async overhead, deterministic scheduling - **UNIQUE TO LIFEGUARD** ✅\n3. **WAL-Based Replica Routing** - Automatic health monitoring - **UNIQUE TO LIFEGUARD** (🟡 Status unclear)\n4. **TTL-Based Active Set** - Adaptive caching - **UNIQUE TO LIFEGUARD** (🟡 Status unclear)\n5. **DeriveLinked Macro** - Multi-hop relationship code generation - **COMPETITIVE ADVANTAGE** ✅ (SeaORM doesn't have this)\n6. **Session/Unit of Work** - Identity map, automatic change tracking - **NOT IN OTHER RUST ORMs** (❌ Not yet implemented)\n\n**Where Lifeguard Matches or Exceeds:**\n- ✅ Complete SeaORM API parity (67% feature coverage, core ORM complete)\n- ✅ Relations system with composite keys and eager/lazy loading\n- ✅ Query builder with 95% method coverage\n- ✅ Better performance potential (2-5× faster on hot paths - architectural)\n- ✅ Lower memory footprint (architectural)\n- ✅ Predictable latency (architectural)\n\n**Trade-offs:**\n- ❌ PostgreSQL-only (by design - enables advanced features)\n- ❌ Requires `may` coroutine runtime (not Tokio)\n- ❌ Smaller ecosystem (newer project)\n- ⚠️ Some promised features not yet implemented (validators, soft deletes, scopes, etc.)\n\n### Performance Comparison (Estimated)\n\n| Metric | Lifeguard | SeaORM | Diesel | SQLx |\n|--------|-----------|--------|--------|------|\n| **Simple Query Latency** | 0.1-0.5ms | 0.5-2ms | 0.2-1ms | 0.5-2ms |\n| **Hot Path Throughput** | 2-5× faster | Baseline | 1-2× faster | Baseline |\n| **Small Query Overhead** | Minimal | Future allocation | Minimal | Future allocation |\n| **Memory per Connection** | ~100 bytes | ~1-2 KB | ~100 bytes | ~1-2 KB |\n| **Concurrent Connections** | 800+ (1MB stack) | Limited by Tokio | Limited by threads | Limited by Tokio |\n| **p99 Latency** | \u003c 5ms (predictable) | 5-20ms (variable) | \u003c 5ms (predictable) | 5-20ms (variable) |\n\n*Note: Performance numbers are estimates based on architecture. Actual benchmarks will be published after implementation.*\n\n### Ecosystem Compatibility\n\n**⚠️ Important: BRRTRouter and Lifeguard are a parallel ecosystem, separate from async/await Rust.**\n\nThese are **two incompatible worlds** with the only commonality being Rust itself:\n\n| Ecosystem | Runtime | ORM Options | Incompatible With |\n|-----------|---------|-------------|-------------------|\n| **BRRTRouter + Lifeguard** | `may` coroutines | Lifeguard only | SeaORM, Diesel (async), SQLx, Tokio |\n| **Tokio + Async ORMs** | `async/await` | SeaORM, Diesel, SQLx | BRRTRouter, Lifeguard, `may` |\n\n**You cannot mix and match.** If you're using BRRTRouter, you **must** use Lifeguard. The async/await ORMs (SeaORM, Diesel, SQLx) are fundamentally incompatible with the `may` coroutine runtime.\n\n### When to Use Each Ecosystem\n\n**Use BRRTRouter + Lifeguard if:**\n- ✅ You're building with **BRRTRouter** (the coroutine API framework)\n- ✅ You need **distributed cache coherence** (LifeReflector - unique to Lifeguard)\n- ✅ You need **extreme scale** (millions of requests/second)\n- ✅ You need **predictable latency** (API routers, real-time systems)\n- ✅ You're **PostgreSQL-only** (enables advanced features)\n- ✅ You want **Oracle Coherence-level functionality**\n\n**Use Tokio + Async ORMs if:**\n- ✅ You're using **Tokio/async-await** runtime\n- ✅ You need **multi-database support** (PostgreSQL, MySQL, SQLite, MSSQL)\n- ✅ You want **mature, well-documented ORMs** (SeaORM, Diesel, SQLx)\n- ✅ You don't need distributed cache coherence\n- ✅ You're building traditional async/await microservices\n\n**The choice is made at the ecosystem level, not the ORM level.** Once you choose BRRTRouter, Lifeguard is your only ORM option. Once you choose Tokio, you can choose between SeaORM, Diesel, or SQLx—but you cannot use BRRTRouter.\n\n---\n\n## 🚀 Performance\n\n**Target Performance:**\n- 2-5× faster than async ORMs on hot paths\n- 10×+ faster on small queries (no future allocation overhead)\n- Predictable p99 latency (\u003c 5ms for simple queries)\n- Lower memory footprint than async alternatives\n\n**Real-World Use Cases:**\n- **BRRTRouter**: High-throughput API routing with sub-millisecond database access (100,000+ requests/second)\n- **High-Scale Microservices**: Applications requiring millions of requests/second with limited database connections\n- **Low-Latency Systems**: Real-time applications needing predictable p99 latency (\u003c 5ms) for database operations\n\n---\n\n## 📚 Documentation\n\n- [Architecture Overview](./docs/ARCHITECTURE.md)\n- [Epics \u0026 Stories](./docs/EPICS/)\n- [SeaORM Feature Audit](./docs/EPICS/Epic_02/SEAORM_AUDIT.md)\n- [Competitive ORM Analysis](./docs/EPICS/COMPETITIVE_ORM_ANALYSIS.md)\n- [Missing Features Analysis](./docs/EPICS/MISSING_FEATURES_ANALYSIS.md)\n- [Blog Post](./docs/wip/LIFEGUARD_BLOG_POST.md)\n\n---\n\n## 🤝 Contributing\n\nLifeguard is being rebuilt from scratch. We welcome:\n- 📝 Documentation improvements\n- 🐛 Bug reports\n- 💡 Feature suggestions\n- 🧪 Testing and feedback\n\nSee [EPICS](./docs/EPICS/) for current development priorities.\n\n\n---\n\n## 📜 License\n\nLicensed under Apache-2.0.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicroscaler%2Flifeguard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicroscaler%2Flifeguard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicroscaler%2Flifeguard/lists"}