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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
Google Online Security Blog
Google Online Security Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
T
Threat Research - Cisco Blogs
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
Lohrmann on Cybersecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Forbes - Security
Forbes - Security
P
Palo Alto Networks Blog
Schneier on Security
Schneier on Security
S
Schneier on Security
T
Tor Project blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
WordPress大学
WordPress大学
The Hacker News
The Hacker News
Hacker News - Newest:
Hacker News - Newest: "LLM"
罗磊的独立博客
Application and Cybersecurity Blog
Application and Cybersecurity Blog
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
C
Check Point Blog
Stack Overflow Blog
Stack Overflow Blog
Blog — PlanetScale
Blog — PlanetScale
雷峰网
雷峰网
S
Security @ Cisco Blogs
PCI Perspectives
PCI Perspectives
Spread Privacy
Spread Privacy
W
WeLiveSecurity
SecWiki News
SecWiki News
A
About on SuperTechFans
H
Help Net Security
博客园 - 司徒正美
Recent Commits to openclaw:main
Recent Commits to openclaw:main
爱范儿
爱范儿
S
Securelist
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
月光博客
月光博客
Jina AI
Jina AI
博客园 - 叶小钗
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
S
Secure Thoughts
The Cloudflare Blog
美团技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & 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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I Built a Real-Time Precious Metals Price Feed for 30,000 Concurrent Users in Laravel
Rana Subhan · 2026-05-23 · via DEV Community

How I Built a Real-Time Precious Metals Price Feed for 30,000 Concurrent Users in Laravel

Architecture walkthrough: Laravel Reverb, WebSocket broadcasting, Redis pub/sub, and the tricks that make it hold under real load.


The Problem

A live precious metals trading platform needs to push gold and silver price updates to every connected user the moment a tick arrives — not every 5 seconds via polling, not via a REST endpoint they hammer on a timer. Real-time. Sub-second latency. And it needs to handle 30,000 simultaneous connections without melting.

This post walks through exactly how I built this using Laravel 11, Laravel Reverb, Redis, and a few architectural decisions that made the difference between a demo and something production-ready.


Stack

  • Laravel 11 + PHP 8.2
  • Laravel Reverb — self-hosted WebSocket server (replaces Pusher)
  • Laravel Echo — frontend WebSocket client
  • Redis — pub/sub backbone + cache
  • Laravel Horizon — queue worker monitoring
  • MySQL 8 — OHLCV candle storage with covering indexes

Full source: github.com/Hafiz-M-Subhan/laravel-precious-metals-platform


Architecture Overview

Price Feed (external API)
        ↓
  PriceService::ingestTick()
        ↓
  DB update + Redis cache (5s TTL)
        ↓
  broadcast(new PriceUpdated($asset))
        ↓
  Laravel Reverb (WebSocket server)
        ↓
  prices.XAU channel → 30k subscribers

Enter fullscreen mode Exit fullscreen mode

The key insight: the database is not in the hot path for subscribers. Price data flows through Redis and directly out via WebSocket. The DB only gets written once per tick, not read 30,000 times.


Step 1 — The Event

The PriceUpdated event is what gets broadcast. The most important decisions are:

Which channel? Public, so unauthenticated visitors on the live page receive ticks too.

What payload? As small as possible. Every extra byte is multiplied by 30,000.

class PriceUpdated implements ShouldBroadcast
{
    public function broadcastOn(): array
    {
        return [
            new Channel("prices.{$this->asset->symbol}"),
            new PresenceChannel('live-event'), // carries viewer count
        ];
    }

    public function broadcastWith(): array
    {
        // 7 fields — deliberately minimal
        return [
            'symbol'     => $this->asset->symbol,
            'spot'       => (float) $this->asset->spot_price,
            'bid'        => (float) $this->asset->bid_price,
            'ask'        => (float) $this->asset->ask_price,
            'change_pct' => (float) $this->asset->daily_change_pct,
            'direction'  => $this->asset->spot_price > $this->previousPrice ? 'up' : 'down',
            'ts'         => now()->toIso8601String(),
        ];
    }

    // Skip broadcast if price moved less than 0.001% — kills ~80% of noise
    public function broadcastWhen(): bool
    {
        if ($this->previousPrice == 0) return true;
        $change = abs(($this->asset->spot_price - $this->previousPrice) / $this->previousPrice);
        return $change >= 0.00001;
    }
}

Enter fullscreen mode Exit fullscreen mode

The broadcastWhen() gate is underused in most Laravel projects. In a metals feed, prices sometimes tick the same value repeatedly. Without filtering, you're broadcasting thousands of no-op messages to 30,000 clients. With it, you cut ~80% of queue messages.


Step 2 — The WebSocket Server (Laravel Reverb)

Laravel Reverb is Laravel's official self-hosted WebSocket server, released in 2024. Before Reverb, you either paid for Pusher or ran a separate Node.js server (Soketi, etc.). Reverb runs as a native PHP process:

php artisan reverb:start --host=0.0.0.0 --port=8080

Enter fullscreen mode Exit fullscreen mode

In config/broadcasting.php:

'reverb' => [
    'driver'  => 'reverb',
    'app_id'  => env('REVERB_APP_ID'),
    'app_key' => env('REVERB_APP_KEY'),
    'app_secret' => env('REVERB_APP_SECRET'),
    'options' => [
        'host' => env('REVERB_HOST', '0.0.0.0'),
        'port' => env('REVERB_PORT', 8080),
        'scheme' => env('REVERB_SCHEME', 'http'),
    ],
],

Enter fullscreen mode Exit fullscreen mode

Reverb uses a non-blocking event loop under the hood (ReactPHP). It handles thousands of concurrent connections on a single process — no thread-per-connection model like traditional PHP.


Step 3 — Redis as the Backbone

Redis does two jobs here:

1. Price cache — every tick writes to Redis with a 5-second TTL. API responses read from Redis, not MySQL. Under a burst of requests (live event with 30k viewers all hitting /api/v1/assets), the DB sees exactly 0 extra reads.

// PriceService::ingestTick()
Cache::put("asset:price:{$symbol}", [
    'spot' => $spot, 'bid' => $bid, 'ask' => $ask,
    'ts'   => now()->toIso8601String(),
], 5); // 5 seconds

Enter fullscreen mode Exit fullscreen mode

2. Queue backend — the broadcast job goes through Redis queues, not the database. This is critical. QUEUE_CONNECTION=redis in .env. Database queues serialize and will struggle under a price feed that fires every 2 seconds across 4 metals.

Horizon monitors all of this with a real dashboard at /horizon. You can see queue throughput, failed jobs, and worker load in real time.


Step 4 — OHLCV Candle Storage

Every tick needs to update the current 1-minute candle (open, high, low, close). Naive approach: SELECT + UPDATE. At 30 ticks/minute across 4 metals, that's 120 roundtrips per minute, plus locking issues.

Better approach: upsert() — one query, atomic, no SELECT needed:

PriceHistory::upsert(
    [[
        'asset_id'    => $assetId,
        'resolution'  => '1m',
        'open'        => $price,  // only set on INSERT
        'high'        => $price,
        'low'         => $price,
        'close'       => $price,
        'volume'      => 0,
        'recorded_at' => now()->startOfMinute(),
    ]],
    uniqueBy: ['asset_id', 'resolution', 'recorded_at'],
    update: [
        'high'  => DB::raw("GREATEST(high, {$price})"),
        'low'   => DB::raw("LEAST(low, {$price})"),
        'close' => $price,
    ],
);

Enter fullscreen mode Exit fullscreen mode

The unique index on (asset_id, resolution, recorded_at) makes this both fast and idempotent — if the same tick somehow arrives twice, nothing breaks.


Step 5 — The Frontend (Laravel Echo)

import Echo from 'laravel-echo';
import Pusher from 'pusher-js'; // Echo uses Pusher protocol even with Reverb

window.Pusher = Pusher;

const echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT,
    forceTLS: false,
    enabledTransports: ['ws', 'wss'],
});

// Subscribe to gold price updates
echo.channel('prices.XAU')
    .listen('.price.updated', (data) => {
        updatePriceTicker(data.symbol, data.spot, data.direction);
    });

// Presence channel — get viewer count for live event page
echo.join('live-event')
    .here((users) => setViewerCount(users.length))
    .joining(() => setViewerCount(prev => prev + 1))
    .leaving(() => setViewerCount(prev => prev - 1));

Enter fullscreen mode Exit fullscreen mode

The presence channel gives you live viewer count for free — the same mechanism Kettner uses for their live event page that peaks at 30,000 simultaneous viewers.


Performance Numbers

Scenario Without optimization With optimization
API under burst (1k req/s) MySQL: 1000 reads/s MySQL: ~0 reads (Redis cache)
Queue messages per minute ~120 raw ticks ~25 (broadcastWhen filters)
Candle upserts 2 queries (SELECT+UPDATE) 1 query (upsert)
Connection overhead 30k × polling interval 1 persistent connection per user

Running It Locally

git clone https://github.com/Hafiz-M-Subhan/laravel-precious-metals-platform.git
cd laravel-precious-metals-platform
docker compose up -d          # MySQL + Redis + Elasticsearch + Reverb + Horizon
php artisan migrate --seed
php artisan reverb:start
php artisan horizon
php artisan prices:simulate --interval=2  # simulates live price feed

Enter fullscreen mode Exit fullscreen mode

The simulator uses Geometric Brownian Motion to generate realistic price movements — the same model used in Black-Scholes options pricing.


What I'd Do Differently at True Scale

  1. Horizontal Reverb scaling — multiple Reverb nodes behind a load balancer, using Redis pub/sub to sync broadcasts across nodes
  2. Separate read replicas for candle chart queries — OHLCV history doesn't need the primary DB
  3. Message compression — at 30k subscribers, gzip on WebSocket frames saves significant bandwidth
  4. Backpressure handling — slow consumers should be detected and disconnected before they cause memory pressure on the Reverb process

Source Code

Full project on GitHub: github.com/Hafiz-M-Subhan/laravel-precious-metals-platform

Includes: models, events, jobs, services, Filament 3 admin panel, Docker Compose, migrations, and a price simulator.


Tags: #laravel #php #websocket #redis #architecture