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

推荐订阅源

Martin Fowler
Martin Fowler
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
罗磊的独立博客
雷峰网
雷峰网
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
B
Blog RSS Feed
腾讯CDC
Apple Machine Learning Research
Apple Machine Learning Research
D
Docker
Recent Announcements
Recent Announcements
T
Tailwind CSS Blog
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Vercel News
Vercel News
小众软件
小众软件
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
I
InfoQ
S
SegmentFault 最新的问题

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
The Day Our Configs Were Backwards (And How Rust Fixed It)
pretty ncube · 2026-05-27 · via DEV Community

The Problem We Were Actually Solving

Our game server at Veltrix had a leak that grew by 1.2MB per second under load. No stack traces, no panics—just the alloc counter in /proc/self/status climbing like a drunk spider on caffeine. The game loop looked innocent:

while let Some(player) = next_player() {
 handle_player(player); // Nothing allocates here, right?
}

Enter fullscreen mode Exit fullscreen mode

Right? We were using Rust with Tokio, so we assumed the borrow checker had our back. Turns out, our next_player was actually a tokio::mpsc::Receiver that buffered every message indefinitely because we'd tuned the channel size to 1024—never realizing it defaulted to unbounded capacity.

The moment I realized the language couldn't save us from our own configuration was when I ran tokio-console and saw 4,096 pending move requests lingering in the channel. Each request was a small struct, but 4k was already pushing us toward OOM.

What We Tried First (And Why It Failed)

First attempt: blame the runtime. We tried switching Tokio's scheduler from multi-threaded to current-thread, thinking fewer threads would reduce allocations. It dropped allocations by 15%, but the leak persisted.

Then we tried limiting the channel explicitly:

let (tx, rx) = tokio::sync::mpsc::channel(128);

Enter fullscreen mode Exit fullscreen mode

We naively assumed 128 was reasonable. Wrong. In production traffic, spikes of 500 concurrent players meant we hit backpressure immediately. Players reported timeouts when the channel filled up.

Our third attempt was to increase the bound to 1024, the default. This worked for a week—until memory shot up again. The real issue wasn't capacity; it was lifetime.

Every message in the channel held a String for the player's session token. When a player disconnected, we dropped the sender, but the receiver kept the last message alive because the channel's internal buffer held a reference. We were leaking session tokens with every disconnect.

The Architecture Decision

We finally traced it to tokio::sync::mpsc using Arc<Message> internally. Even after dropping the sender, the Arc kept the message alive until processed. With 10k players per match, that was 10k strings in limbo.

The fix wasn't just configuration—it was ownership. We switched to tokio::sync::mpsc::unbounded_channel with an explicit backpressure layer using Semaphore:

let sem = Arc::new(Semaphore::new(1024));
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

while let Some(player) = rx.recv().await {
 let permit = sem.clone().acquire_owned().await?;
 tokio::spawn(async move {
 handle_player(player).await;
 drop(permit); // Release capacity
 });
}

Enter fullscreen mode Exit fullscreen mode

No more unbounded growth. The semaphore capped concurrency at 1k, and Rust's ownership model ensured tokens were dropped immediately when the permit was released.

But this wasn't free. We now had to handle backpressure explicitly. Players would get Service Unavailable if the semaphore was full. We had to add telemetry:

if sem.available_permits() == 0 {
 metrics::counter!("backpressure_rejects").increment(1);
}

Enter fullscreen mode Exit fullscreen mode

What The Numbers Said After

After the switch, memory stabilized:

Metric Before After
Allocated heap (RSS) 4.2GB 1.8GB
GC cycles (if we'd used GC) N/A 0
Channel latency p99 12ms 8ms
Backpressure rejections 0 23 per minute at peak

We ran a 24-hour load test with 50k simulated players. RSS never exceeded 2.1GB, and the allocator reported 0 leaks in jemalloc's prof.active after shutdown.

The semaphore added 4ms to p99 latency when full, but we accepted that tradeoff for stability.

What I Would Do Differently

I would have started with tokio-console on day one. We wasted weeks assuming the runtime was the issue. Had we run:

tokio-console subscribe tokio/channel/size

Enter fullscreen mode Exit fullscreen mode

weeks earlier, we'd have seen messages piling up immediately.

Also, I wouldn't have trusted defaults for anything involving player data. Tok's default channel size is usize::MAX—unbounded. Tokio's time module defaults to 1ms for timers, which caused jitter under load. Every default must be questioned when you're handling real players.

Finally, don't treat Rust as a silver bullet for config issues. The compiler guarantees no leaks within a single crate, but leaks between crates or through external tools (like Tokio) are your problem. Configuration isn't a runtime concern—it's an ownership concern.

And never assume your game loop is safe just because you're using Rust.