惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
F
Fortinet All Blogs
C
Check Point Blog
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Blazing Fast Analytics: Materialized Views in Larave
Prajapati Paresh · 2026-06-19 · via DEV Community

The Real-Time Analytics Bottleneck

In enterprise B2B SaaS platforms at Smart Tech Devs, the executive dashboard is the most critical page. Clients want to log in and instantly see their Monthly Recurring Revenue (MRR), total active users, and churn rates. The standard developer reflex is to write complex Eloquent aggregates: joining the users, subscriptions, and invoices tables, calculating sums, and grouping by month.

When your database has 10,000 rows, this query takes 50 milliseconds. When your database has 5 million rows, this query takes 6 seconds. If 100 executives log into their dashboards at 9:00 AM, your PostgreSQL database will attempt to run 100 simultaneous 6-second aggregate queries. The CPU spikes to 100%, connection pools exhaust, and the platform crashes. You cannot calculate heavy analytics on the fly. You must pre-compute them using Materialized Views.

The Solution: PostgreSQL Materialized Views

A standard SQL View is just a saved query; it still runs the heavy math every time you call it. A Materialized View, however, runs the heavy math once and saves the result as a physical, queryable table on your disk.

When the executive loads their dashboard, they aren't scanning 5 million rows. They are querying a tiny, pre-calculated 10-row materialized view table. The response time drops from 6 seconds to 2 milliseconds.

Step 1: Architecting the Migration

Laravel doesn't have native schema builders for Materialized Views, so we utilize raw SQL within our migration files to define the complex aggregate logic.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class CreateMonthlyRevenueMaterializedView extends Migration
{
    public function up(): void
    {
        // 1. Create the Materialized View
        DB::statement('
            CREATE MATERIALIZED VIEW monthly_tenant_revenue AS
            SELECT 
                tenant_id,
                DATE_TRUNC(\'month\', created_at) AS billing_month,
                COUNT(id) as total_invoices,
                SUM(amount) as total_revenue
            FROM invoices
            WHERE status = \'paid\'
            GROUP BY tenant_id, DATE_TRUNC(\'month\', created_at)
        ');

        // 2. Add a Unique Index to allow for CONCURRENT refreshes later
        DB::statement('
            CREATE UNIQUE INDEX monthly_tenant_revenue_unique_idx 
            ON monthly_tenant_revenue (tenant_id, billing_month);
        ');
    }

    public function down(): void
    {
        DB::statement('DROP MATERIALIZED VIEW IF EXISTS monthly_tenant_revenue;');
    }
}

Step 2: Refreshing the Data Asynchronously

Because the data is saved physically, it will go stale as new invoices are paid. We must refresh it. Instead of refreshing it when a user clicks a button (which blocks their request), we set up a background Laravel Job to refresh it quietly every hour.


namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class RefreshRevenueAnalytics implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function handle(): void
    {
        // The CONCURRENT keyword is absolute magic. 
        // It allows PostgreSQL to update the materialized view in the background 
        // WITHOUT locking the table. Users can still read the old data while the new data generates!
        DB::statement('REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_tenant_revenue;');
    }
}

The Engineering ROI

By shifting heavy analytics to Materialized Views, you completely decouple your read performance from your data volume. Your dashboards load instantly regardless of how many millions of rows exist in your core tables. You transform unpredictable, CPU-heavy dashboard loads into flat, O(1) lightning-fast queries, guaranteeing a premium executive user experience.