AI 资讯
Making a WebSocket survive Chrome's Manifest V3
The bug reports all sounded the same. "It disconnected again." No error, no warning, nothing on screen to explain it. Someone would open a GitHub issue, start a planning-poker vote, then stop to actually read the thing they were estimating. Thirty seconds later they'd look back and the room had quietly gone still. Other people's votes weren't showing up, and their own weren't reaching the room. It had simply stopped, without a word. If you've ever built anything real on Chrome's Manifest V3, you can probably guess where this is going. The socket didn't drop because the network hiccupped. It dropped because Chrome reached over and killed the process it was living in. This is the story of that bug, and what it actually takes to keep a WebSocket alive inside a Manifest V3 extension. TL;DR: Manifest V3 runs your background code in a service worker that Chrome terminates after ~30s idle. If your WebSocket lives there, it dies with it, silently. The fix is three parts: a heartbeat so extension activity keeps the worker awake, auto-reconnect that pulls a fresh snapshot so drops are invisible, and a try/catch around every port message because the worker can die between your null-check and the call. Why the socket doesn't live where you'd expect First, some context on how the extension is wired, because it explains why this bug was even possible. It puts a button on GitHub issues and boards. Click it, and a live planning-poker room opens right there in the page. Votes flow over a WebSocket to a Cloudflare Durable Object that owns the room's state. Standard real-time stuff. The obvious place to open that socket is the content script, the code injected into the GitHub page. That's where the UI lives, so why not open the socket right next to it? Firefox is why not. A content script runs in the page's world, which means it inherits the page's Content Security Policy. GitHub ships a strict connect-src , and Firefox enforces it against content scripts. Try to open wss://… from the
AI 资讯
Building Resilient Real-Time Systems: WebSockets, Redis, and Strategies for High Availability
Originally published on tamiz.pro . Real-time systems are at the heart of modern interactive applications, from chat platforms to collaborative editing tools and financial dashboards. Delivering a seamless, low-latency experience while ensuring high availability and fault tolerance presents significant architectural challenges. This deep-dive explores how WebSockets, for persistent client-server communication, and Redis, for state management and pub/sub, can be combined with strategic design patterns to build resilient real-time systems. The Core Challenge of Real-Time Resilience The primary challenge in real-time systems is maintaining continuous connectivity and data flow despite inevitable network issues, server failures, or application restarts. A single point of failure can disrupt numerous active user sessions, leading to a poor user experience. Resilience, in this context, means the system's ability to recover gracefully from failures and continue operating, even if in a degraded state. WebSockets: The Foundation for Real-Time Communication WebSockets provide a full-duplex communication channel over a single TCP connection, enabling persistent, low-latency message exchange between client and server. Unlike traditional HTTP requests, WebSockets keep the connection open, eliminating the overhead of connection setup for each message. However, managing a large number of concurrent WebSocket connections and ensuring their availability across a distributed system requires careful design. WebSocket Server Scalability and Load Balancing Directly load balancing WebSocket connections using standard HTTP load balancers can be tricky because WebSockets are long-lived. Sticky sessions are often employed to ensure a client consistently connects to the same backend server. While this works, it can lead to uneven server load and complicates server replacement during failures. A more robust approach involves a dedicated WebSocket gateway layer that can manage connections and
AI 资讯
Building a Production-Ready Risk Management Engine for Algorithmic Trading
Part: 4 of 18 About this series This series documents the engineering evolution of a production-ready algorithmic trading platform in Python. It focuses on architecture, state management, execution, real-time data processing, persistence, and the engineering decisions that transformed a simple trading bot into a production-ready platform. In Part 3: Building a Production-Ready Position Manager for Algorithmic Trading , I described the component responsible for maintaining persistent position state throughout the entire trade lifecycle. Read Part 3 here: https://dev.to/pydevtop/building-a-production-ready-position-manager-for-algorithmic-trading-55n4 The Position Manager could remember every open position. The next challenge was deciding what should happen to those positions as market conditions continuously changed. Project Website This article is part of the engineering story behind the Bybit Signal Trading Platform . If you'd like to learn more about the project, see additional screenshots, features and technical details, visit: https://py-dev.top/application-software/bybit-signal-trading-bot The Problem Was Never Stop Loss If someone had asked me during the first weeks of development where the Stop Loss logic should live, I wouldn't have hesitated. Inside the Trade Execution Engine. Where else? The engine already received TradingView webhooks. It validated incoming requests. It calculated Take Profit. It opened positions. Adding one more calculation felt completely natural. The implementation looked something like this. signal = receive_signal () validate ( signal ) entry = execute_order ( signal ) stop_loss = calculate_stop_loss ( entry ) take_profit = calculate_take_profit ( entry ) Simple. Readable. Everything related to opening a trade existed in one place. At that moment there was absolutely no reason to introduce another component. There was only one trading pair. Only one open position. No persistence. No restart recovery. No Break Even. No Trailing Stop.
AI 资讯
Building a Real Time Sports Scoring Engine with WebSockets and DynamoDB Streams
The Problem Sports scoring sounds simple. One team scores a point, the number goes up, everyone sees it. But when you build it as a web application that needs to work on courtside tablets, spectator phones, and wall mounted displays simultaneously, with voice commands and tap controls, the architecture becomes more interesting. The project was Scoring AI, a voice enabled match scoring application for sports courts. Players start a match, share a link, and control the scoreboard from any device. The backend handles real time state synchronization, optimistic locking, idempotent score updates, rate limiting, and WebSocket broadcasting. The team was small. Me and a coworker who handled the CI/CD side. We were at the same level, both full stack, and we designed the system together. He focused on the deployment pipeline and infrastructure automation. I focused on the application layer, the real time system, and the frontend. But the architecture decisions were shared. This article covers the technical decisions we made and how patterns from previous projects influenced them. Why DynamoDB for Live Matches The match scoring data is different from the business data around it. A match lasts about an hour, gets updated frequently, and needs to be read by many viewers at once. After the match is complete, it is archived and rarely accessed. I had seen what happens when you put high frequency state updates into a relational database on a previous project. Row locks, contention, connection pool exhaustion. For Scoring AI, we used DynamoDB for the live match state and PostgreSQL for everything else. The hot path needed fast writes, optimistic locking, and automatic cleanup of abandoned matches. DynamoDB provides all of these. The version field on each match record acts as an optimistic lock. Every score update is a conditional write that checks the version has not changed. The cold path uses PostgreSQL through Kysely for user profiles, subscriptions, pricing plans, payment histor
AI 资讯
Deploying a real-time multiplayer game on Railway
This post contains Railway referral links. If you sign up through one I get a bit of credit. I build Old Light , a real-time strategy game that runs in the browser. Claim stars, grow an economy, send fleets, all while other players and NPC empires do the same. The second a build finishes or a fleet lands, the server pushes it to every connected client over a WebSocket. That last part, a long-lived server holding an open socket, rules out most of the usual hosts. Here's what it ruled in. Why not Vercel or Netlify Serverless shines when your backend is stateless functions. It's the wrong shape the moment you need a socket that stays open: socket.io wants one process that lives for the whole session, and serverless boots per request and then freezes. You can bolt on a managed WebSocket service, but that's a second system to run and pay for. Railway runs your service as a normal long-lived process, so socket.io just connects. Fly.io does this too with more knobs to turn. I wanted to ship, so Railway won. Monorepo, two services Old Light is an npm workspaces monorepo: a shared types package, an Express plus TypeORM plus socket.io API, and a Vite web app served by a small Express server. On Railway that's two services on the same repo, each with its own root directory and build command, shared built first. They deploy as separate origins, so the web app reads the API's URL from VITE_API_URL . Vite bakes that in at build time, so it's a build variable, not a runtime one. Postgres is a plugin that injects DATABASE_URL , and production runs migrations rather than synchronize . WebSockets need nothing special until you run more than one instance, at which point you'd add a Redis socket.io adapter. I haven't left a single box yet. A healthcheck that stops version skew Two services don't go live at the same instant. Push a commit that touches both, the web finishes first, and for a minute your new frontend is calling API routes that don't exist yet. It 404s, then heals itself o
开发者
WebSocket Reconnection That Actually Works: Auto-Reconnect Guide for Trading Bots
This post was originally published on MatrixTrak.com — the production reliability toolkit for trading bot operators and .NET engineers. Complete WebSocket auto-reconnect guide for trading bots. Implement automatic reconnection with exponential backoff, heartbeat ping-pong, message gap detection, and state recovery. WebSocket connections drop. Not maybe. Definitely. Exchanges reset connections every 24 hours. Networks glitch. Load balancers rotate. HTTP proxies timeout. Your trading bot will experience disconnects. The question isn't whether you'll disconnect—it's whether your bot recovers correctly when you do. If you only do three things Implement automatic reconnection with exponential backoff and jitter. Track sequence numbers to detect missed messages. Always verify state via REST after reconnect. Never trust WebSocket alone. WebSocket Auto-Reconnect Quick Start If you just need a working auto-reconnect loop right now, here's the minimum viable implementation: class AutoReconnectWebSocket { private ws : WebSocket | null = null ; private reconnectAttempts = 0 ; private maxRetries = 10 ; private shouldReconnect = true ; async connect ( url : string ): Promise < void > { return new Promise (( resolve , reject ) => { this . ws = new WebSocket ( url ); this . ws . onopen = () => { this . reconnectAttempts = 0 ; resolve (); }; this . ws . onclose = ( event ) => { if ( this . shouldReconnect ) { const delay = this . backoff (); console . log ( `[AutoReconnect] Closed ${ event . code } . Reconnecting in ${ delay } ms` ); setTimeout (() => this . connect ( url ), delay ); } }; this . ws . onerror = () => { /* onclose fires next */ }; }); } private backoff (): number { const base = 1000 ; const max = 30000 ; const delay = Math . min ( base * Math . pow ( 2 , this . reconnectAttempts ++ ), max ); return delay + delay * 0.2 * ( Math . random () * 2 - 1 ); // +20% jitter } close (): void { this . shouldReconnect = false ; this . ws ?. close (); } } This handles the core auto
AI 资讯
Why crypto arbitrage windows close before your REST poll completes
TL;DR : Crypto arbitrage windows on liquid pairs now close in under 100 ms. A REST polling loop typically takes 1–1.5 seconds round-trip. WebSocket delivers the same data in 20–100 ms. If you're still polling REST endpoints for orderbook data in 2026, you're missing the majority of opportunities — not because your strategy is wrong, but because your data plane is fundamentally too slow. This post walks through the math, shows a benchmark I ran on a handful of major exchanges, and provides production-grade Python code for a WebSocket client that handles reconnects, heartbeats, and orderbook reconstruction. 1. The numbers that broke REST polling When I started writing crypto arbitrage bots a few years ago, polling Binance's REST API every 500 ms was perfectly acceptable. Spreads were wide, arbitrage windows lasted multiple seconds, and the orderbook for BTCUSDT moved slowly enough that a half-second-old snapshot was still tradeable. In 2026, the same approach doesn't work. Here are the numbers as they stand today: Metric Value Median crypto arbitrage window on liquid pairs 30–80 ms Window closes in under 100 ms ~90% of cases REST round-trip latency (request → response → JSON parse) 1.0–1.5 seconds WebSocket update delivery latency (push from exchange to client) 20–100 ms The math is brutal. A 100 ms window cannot be caught by a 1500 ms poll. By the time your REST response arrives, the orderbook you're reading is 15 cycles stale. You're not "slow" — you're not even in the same temporal universe as the event you're trying to react to. 2. Why REST is fundamentally slow REST APIs over HTTPS carry overhead that adds up: TCP handshake — three packets to establish, typically 50–150 ms on intercontinental hops. TLS handshake — another full round-trip, 30–100 ms. HTTP request/response — the actual data exchange. JSON parse — depending on payload size, 5–50 ms. Rate-limit budget — most exchanges cap REST to 10–20 requests per second per IP. Polling faster gets you banned. Yes,