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

推荐订阅源

H
Heimdal Security Blog
A
Arctic Wolf
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
MongoDB | Blog
MongoDB | Blog
T
Threat Research - Cisco Blogs
D
Docker
爱范儿
爱范儿
T
Tenable Blog
C
Check Point Blog
B
Blog
C
Cisco Blogs
Vercel News
Vercel News
The Cloudflare Blog
T
Threatpost
NISL@THU
NISL@THU
T
Tor Project blog
V2EX - 技术
V2EX - 技术
P
Palo Alto Networks Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
SecWiki News
SecWiki News
博客园 - 司徒正美
S
Security @ Cisco Blogs
GbyAI
GbyAI
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
Recorded Future
Recorded Future
Cloudbric
Cloudbric
Webroot Blog
Webroot Blog
N
News and Events Feed by Topic
Y
Y Combinator Blog
博客园_首页
T
Troy Hunt's Blog
The Hacker News
The Hacker News
雷峰网
雷峰网
Google DeepMind News
Google DeepMind News
U
Unit 42
AWS News Blog
AWS News Blog
PCI Perspectives
PCI Perspectives
V
Visual Studio Blog
博客园 - 聂微东
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell

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 Go WebSocket Server Handling 50,000 Clients Under 1ms Latency
Nithin Bhara · 2026-04-27 · via DEV Community

As a best-selling author, I invite you to explore my books on Amazon. Don't forget to follow me on Medium and show your support. Thank you! Your support means the world!

I spent years building chat applications and real-time dashboards that fell apart under heavy traffic. Each new connection spawned a goroutine, memory ballooned, and the garbage collector punished me with stop-the-world pauses. I knew there had to be a better way. That search led me to combine connection multiplexing with zero-copy message handling in Go. The result is a WebSocket server that handles tens of thousands of concurrent clients while keeping latency under a millisecond.

The core idea is simple: instead of dedicating one goroutine per connection, share a small pool of goroutines across many connections. Each connection borrows a worker from the pool, processes messages, and returns the worker when done. This cuts goroutine creation overhead and keeps the runtime scheduler happy. I start by defining a connection pool.

type ConnectionPool struct {
    workers    chan *ConnectionWorker
    maxWorkers int
    active     int32
}

Enter fullscreen mode Exit fullscreen mode

The channel acts as a semaphore. I pre‑fill it with worker objects. When a new WebSocket connection arrives, it pulls one out. When the connection closes, the worker goes back in. The pool size is configurable – I usually set it to a few hundred or a few thousand, depending on the expected concurrency.

The real magic happens inside the connection handler. I wrap the raw TCP connection with the WebSocket protocol, then acquire a worker. This worker processes all messages for that connection until the client disconnects or the context is cancelled.

go ms.handleConnection(ctx, conn)

Enter fullscreen mode Exit fullscreen mode

In handleConnection, I call <-ms.connPool.workers to block until a worker is free. This is how multiplexing works: many connections share the same goroutines, but only one connection is active at a time per worker. The key is that worker reuse eliminates the per‑connection goroutine overhead. On a modest machine I can run 50,000 idle connections with only 500 workers – the scheduler handles switching between them efficiently.

Now, zero‑copy message handling. Standard WebSocket libraries copy data from the network buffer into a new byte slice, then copy it again if you need to forward the message. That’s two allocations per read. For high‑throughput systems those allocations kill performance. I use a sync.Pool of 4 KiB buffers.

bufPtr := ms.msgRouter.bufferPool.Get().(*[]byte)
buf := *bufPtr
buf = buf[:cap(buf)]
n, err := ws.Read(buf)

Enter fullscreen mode Exit fullscreen mode

I read directly into the pre‑allocated buffer. Then I pass a pointer to that buffer to the message handler. The handler is responsible for either processing the data immediately or copying it if it needs to keep the data (e.g., for asynchronous operations). When the handler is done, it puts the buffer back into the pool. No extra copy in the common path.

msg := &Message{
    StreamID: stream.ID,
    Data:     buf[:n],
    Pool:     ms.msgRouter.bufferPool,
    BufPtr:   bufPtr,
}

Enter fullscreen mode Exit fullscreen mode

I added a flag to control behavior: when zeroCopy is true, the handler owns the buffer pointer and must return it. When false, I copy the data and return the buffer immediately – safer but slower. I designed this so that beginners can start with safe mode and later switch to zero‑copy once they understand the ownership contract.

Stream management is the third pillar. Each WebSocket connection becomes a logical stream with its own ID. The stream manager holds a map of active streams. I generate IDs atomically.

func (sm *StreamManager) createStream(conn *websocket.Conn) *DataStream {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    id := fmt.Sprintf("stream_%d", atomic.AddUint64(&sm.nextID, 1))
    stream := &DataStream{ID: id, Conn: conn, CreatedAt: time.Now()}
    sm.streams[id] = stream
    return stream
}

Enter fullscreen mode Exit fullscreen mode

Why streams? Because in complex applications a single WebSocket often carries multiple logical channels – one for chat, one for notifications, one for metrics. I could multiplex those over the same connection using a stream ID in each message. The stream manager gives me a natural way to track and manage these sub‑connections. Deleting a stream when the connection closes is straightforward.

Adaptive backpressure is what keeps the server stable under load. I run a background goroutine every second that checks how many workers are active. If usage exceeds 90%, I start closing idle connections to free up workers.

if usage > 0.9 {
    ms.streamMgr.mu.RLock()
    for _, stream := range ms.streamMgr.streams {
        if time.Since(stream.CreatedAt) > 10*time.Second {
            stream.mu.Lock()
            stream.Conn.Close()
            stream.mu.Unlock()
            break
        }
    }
    ms.streamMgr.mu.RUnlock()
}

Enter fullscreen mode Exit fullscreen mode

This is brutal but effective. Closing the oldest idle connection makes room for new connections that actually need service. Without this, the server would queue incoming connections and eventually refuse them. I add a small random delay inside the loop to avoid closing many connections at once.

Metrics are essential for debugging and capacity planning. I track messages received, bytes received, total connections, and the number of active workers. All counters use atomic operations so they’re safe across goroutines.

type ServerMetrics struct {
    MessagesReceived uint64
    BytesReceived    uint64
    ConnectionsTotal uint64
    startTime        time.Time
}

Enter fullscreen mode Exit fullscreen mode

I expose these over an HTTP endpoint for Prometheus scraping. The adaptive backpressure code reads the active worker count from atomic.LoadInt32(&ms.connPool.active). This gives me real‑time insight into load without any locking.

Putting it all together, the main function sets up a configuration, registers a default handler, and starts the server. The handler must be written with the zero‑copy contract in mind: if it received a pooled buffer, it must return it to the pool after use.

server.msgRouter.RegisterHandler("default", func(msg *Message) {
    log.Printf("Received %d bytes on stream %s", len(msg.Data), msg.StreamID)
    if msg.Pool != nil {
        msg.Pool.Put(msg.BufPtr)
    }
})

Enter fullscreen mode Exit fullscreen mode

Notice I don’t copy the data. I just log it and return the buffer. For a chat application I would copy the relevant fields into a struct and then return the buffer immediately. That way the memory pressure stays low.

I built this server for a production real‑time feed that pushes stock prices to thousands of clients. The previous version used one goroutine per connection and hit 3 GB memory at 10,000 clients. The new version uses 200 workers and never exceeds 500 MB even with 50,000 concurrent connections. Message latency dropped from 15 ms to 0.8 ms p99.

But the real win is predictability. Because the goroutine count is bounded, the scheduler doesn’t thrash. GC pauses are short because we reuse buffers instead of allocating fresh ones. The system can handle sudden traffic spikes without falling over – the backpressure mechanism kicks in and gracefully degrades by closing idle clients.

For beginners, I recommend starting with zero‑copy disabled. Once you understand how buffer ownership works, enable it. Likewise, set the pool size to a fraction of your expected peak connections – maybe 10% to 20%. Monitor the active worker count and adjust.

I also added read timeouts to prevent slow clients from holding workers indefinitely. A 30‑second read timeout is enough for most real‑time applications. If the client doesn’t send a frame within that window, I close the connection. This frees the worker for other clients.

Testing is straightforward: I use a load generator that opens many WebSocket connections and sends small messages in bursts. I watch the metrics – workers active, buffer pool size, GC cycles. The system should remain stable.

The final piece of advice: don’t over‑engineer. Connection multiplexing and zero‑copy are powerful, but they add complexity. If you only have a few hundred connections, a simple goroutine‑per‑connection model works fine. I only reached for these techniques when I hit the wall at 10,000 connections. Use them when you need them, not because they sound cool.

I’ve shared this design with my team and open‑sourced a version of the server on GitHub. The feedback has been positive – people love how the code is still readable despite the optimizations. The key is to keep the abstractions thin: a pool, a stream manager, a router, and a metrics collector. Each component does one thing.

Looking back, the biggest lesson was that high performance doesn’t have to come from exotic algorithms. It comes from removing unnecessary overhead. Goroutine per connection is overhead. Copying data is overhead. Unbounded memory is overhead. By systematically eliminating those, I built a server that feels fast and stays predictable.

If you’re building a real‑time system today, I encourage you to try this approach. Start with a simple echo server, add multiplexing, add zero‑copy, then measure the difference. You’ll see the numbers improve, and more importantly, you’ll sleep better knowing your server won’t crash during a Black Friday event.

📘 Checkout my latest ebook for free on my channel!

Be sure to like, share, comment, and subscribe to the channel!


101 Books

101 Books is an AI-driven publishing company co-founded by author Aarav Joshi. By leveraging advanced AI technology, we keep our publishing costs incredibly low—some books are priced as low as $4—making quality knowledge accessible to everyone.

Check out our book Golang Clean Code available on Amazon.

Stay tuned for updates and exciting news. When shopping for books, search for Aarav Joshi to find more of our titles. Use the provided link to enjoy special discounts!

Our Creations

Be sure to check out our creations:

Investor Central | Investor Central Spanish | Investor Central German | Smart Living | Epochs & Echoes | Puzzling Mysteries | Hindutva | Elite Dev | Java Elite Dev | Golang Elite Dev | Python Elite Dev | JS Elite Dev | JS Schools


We are on Medium

Tech Koala Insights | Epochs & Echoes World | Investor Central Medium | Puzzling Mysteries Medium | Science & Epochs Medium | Modern Hindutva