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

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com

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
Drop Traits: The Day We Stopped Restarting Pods Every 8 Hours
speed engine · 2026-05-04 · via DEV Community

Or: how we learned that “eventually” isn’t good enough when you’re bleeding file descriptors


Drop Traits: The Day We Stopped Restarting Pods Every 8 Hours

Or: how we learned that “eventually” isn’t good enough when you’re bleeding file descriptors

Deterministic cleanup means knowing exactly when resources are freed — the difference between memory chaos and predictable system behavior in production environments.

So our video transcoding service was… how do I put this delicately… a complete disaster.

Not in the “everything’s on fire” way. More like the “slow leak that nobody wants to admit is a real problem” way. We were processing 2.4 million videos daily, which sounds impressive until you realize we had to restart every single pod every 8 hours or it would just… die.

Memory would start at a reasonable 2GB per pod. Then climb. And climb. And by hour 7, we’d be sitting at 14GB and sweating, watching the graphs, waiting for the OOM killer to show up like an unwelcome dinner guest.

The numbers were absolutely brutal:

  • Monthly infrastructure costs: $83,000 (ouch)
  • Memory-related incidents: 47 per month (that’s more than one per day)
  • Engineer hours spent firefighting: 120 hours (three full-time weeks!)
  • Sleep quality: terrible (not officially tracked but definitely real)

We tried everything. Profile-guided optimization? Check. Custom memory pools? Built those. Aggressive GC tuning? Oh god, so much tuning. We had engineers who could recite Go GC parameters in their sleep.

Nothing worked consistently.

And then — okay, this is where it gets interesting — we realized the garbage collector wasn’t solving our problem. It was hiding it.

The Thing About “Eventually”

Here’s what I didn’t understand about garbage collection until it bit us. In GC languages, cleanup happens “eventually.” Which sounds fine in theory:

  • File handles close… when the GC runs
  • Network connections terminate… during collection cycles
  • Memory returns to the pool… when there’s pressure

This abstraction is actually really powerful! Until it’s catastrophic. Which, in our case, it very much was.

Our video pipeline was handling temporary files, FFmpeg processes, TCP connections to S3. Pretty standard stuff. In Go, we were doing what everyone does — defer and finalizers:

func processVideo(path string) error {  
    file, err := os.Open(path)  // open the file  
    if err != nil {  
        return err  // bail if it fails  
    }  
    defer file.Close()  // this'll close it... eventually  

    // Process video for like 30 seconds  
    return nil  
}

Enter fullscreen mode Exit fullscreen mode

Looks totally fine, right? This is idiomatic Go. This is what you’re supposed to do.

The problem — and oh boy was this a problem — is that defer doesn't mean "clean this up right now." It means "clean this up when this function returns, but the actual resource release might not happen until the GC feels like it."

Under heavy load? File descriptors just… accumulated. Like plaque. We’d hit the system limit of 65,536 file descriptors and crash with “too many open files” errors while still having 6GB of free memory.

The GC would be sitting there like “memory looks fine to me!” while we’re drowning in open file handles.

Here’s what killed us:

Go metrics that made us cry:

  • File descriptor leaks: 2,300 per hour during peak (that’s 38 per minute!)
  • Average cleanup delay: 14.7 seconds (an eternity in computer time)
  • Memory high-water mark: 14.2GB per pod (why?!)
  • OOM incidents: 47 per month
  • Process restarts: 91 per day (three or four every hour)
  • Monthly cost: $83,000 (we could hire another engineer for this)

When We Discovered Deterministic Cleanup (Finally)

So we rewrote the critical path in Rust. And I know what you’re thinking — “oh great, another ‘Rust is faster’ story.” But that’s not what happened. Not really.

Rust wasn’t faster in the benchmark sense. It was predictable. And predictability, it turns out, is way more valuable than raw speed when you’re trying to sleep at night.

The Drop trait in Rust guarantees — guarantees — that cleanup happens at a precise moment. Not “eventually.” Not “when the GC feels like it.” Right when the value goes out of scope. Period.

struct VideoFile {  
    handle: File,        // the actual file handle  
    path: PathBuf,       // where it lives on disk  
}  

impl Drop for VideoFile {  
    fn drop(&mut self) {  
        // THIS RUNS IMMEDIATELY when VideoFile goes out of scope  
        // Not later. Not when GC runs. RIGHT NOW.  
        println!("Closing: {:?}", self.path);  // log it  
        // file handle closes automatically here  
    }  
}  
fn process_video(path: &Path) -> Result<(), Error> {  
    let video = VideoFile {  
        handle: File::open(path)?,  // open the file  
        path: path.to_path_buf(),   // store the path  
    };  

    // Process the video for 30 seconds or whatever  

    // Drop runs EXACTLY HERE when video goes out of scope  
    // No waiting. No GC. Just immediate cleanup.  
    Ok(())  
}

Enter fullscreen mode Exit fullscreen mode

The impact was… I mean, look at these numbers:

Rust metrics that made us believers:

  • File descriptor leaks: 12 per hour (96% reduction, holy shit)
  • Average cleanup time: under 100 microseconds (not 14 seconds!)
  • Memory high-water mark: 3.1GB per pod (78% reduction!)
  • OOM incidents: 0 per month (ZERO)
  • Process restarts: 0 per day (ZERO)
  • Monthly cost: $22,000 (73% reduction, $61K savings)

Why “When” Matters More Than “How Fast”

The revelation — and this took me embarrassingly long to understand — wasn’t that Rust was faster at cleanup. It’s that knowing when cleanup happens is more valuable than how quickly it happens.

Think about our file handle lifecycle. In Go, it looked like this:

  1. Open file (happens immediately, good)
  2. Use file (totally predictable, fine)
  3. Defer close (scheduled for later, okay I guess)
  4. Wait for GC cycle (wait, how long?)
  5. Finalizer runs (seriously, when though?)
  6. Resource freed (eventually? maybe?)

Compare that to Rust:

  1. Open file (immediate)
  2. Use file (predictable)
  3. Drop runs (scope ends, cleanup happens NOW)
  4. Resource freed (immediate)

This difference compounded across 2.4 million videos per day. With Go, file descriptor usage was probabilistic. We had to overprovision by 4x to handle worst-case scenarios. Like, we needed capacity for “what if the GC doesn’t run for a while?” scenarios.

With Rust? Resource usage became a simple function: concurrent videos being processed × resources per video. That’s it. No probability distributions. No worst-case scenarios. Just math.

How We Actually Built This Thing

Okay so here’s how we restructured everything around Drop semantics. And honestly, once you get the pattern, it’s kind of beautiful.

Pattern 1: Scoped Resource Lifetimes

We wrapped every external resource in a struct with Drop:

struct TempWorkspace {  
    dir: TempDir,      // temporary directory handle  
    max_size: u64,     // size limit for safety  
}  

impl Drop for TempWorkspace {  
    fn drop(&mut self) {  
        // This ALWAYS runs when TempWorkspace goes out of scope  
        // Even if there's a panic. Even if there's an error.  
        // ALWAYS.  
        let _ = fs::remove_dir_all(&self.dir);  // nuke the temp dir  
        // ignore errors because we're in Drop, nothing we can do  
    }  
}  
struct FFmpegProcess {  
    child: Child,         // the spawned process  
    timeout: Duration,    // how long to wait before killing  
}  
impl Drop for FFmpegProcess {  
    fn drop(&mut self) {  
        // Force-kill any hung processes  
        // Can't have zombie FFmpeg processes hanging around  
        let _ = self.child.kill();  // terminate immediately  
        // ignore error if already dead  
    }  
}

Enter fullscreen mode Exit fullscreen mode

This architecture eliminated an entire class of bugs. Like, just made them impossible.

Before, temp files would accumulate during high-load periods. We had cron jobs running every hour to manually clean them up. Cron jobs! For cleanup! In 2023!

With Drop? Automatic. Immediate. Our temp disk usage went from 847GB to 23GB. Just from this one change.

Pattern 2: RAII for Network Connections

RAII (Resource Acquisition Is Initialization) became our pattern for everything I/O related:

struct S3Connection {  
    client: S3Client,    // the actual S3 client  
    bucket: String,      // which bucket we're using  
    session_id: String,  // for tracking/metrics  
}  

impl Drop for S3Connection {  
    fn drop(&mut self) {  
        // Log when we're done with this connection  
        // Perfect for metrics and monitoring  
        metrics::record_session_end(  
            &self.session_id  // track this specific session  
        );  
        // client closes automatically  
    }  
}

Enter fullscreen mode Exit fullscreen mode

This gave us perfect connection accounting. At any moment, we knew exactly how many active S3 sessions existed. Not “approximately.” Exactly.

Before, with Go’s deferred cleanup, our monitoring showed “ghost” connections. Connections that were closed but… not really? Still consuming resources somewhere in limbo, waiting for the GC to notice them.

With Drop? No ghosts. Just real connections that existed, and then didn’t.

Pattern 3: Memory-Mapped Files (The Big One)

For large video files — anything over 2GB — we used memory-mapped I/O. And this is where Drop really shined:

struct MappedVideo {  
    mmap: MmapMut,  // the memory-mapped region  
    size: usize,    // total size in bytes  
}  

impl Drop for MappedVideo {  
    fn drop(&mut self) {  
        // Guaranteed unmap - returns virtual pages to OS IMMEDIATELY  
        // No waiting for GC to decide memory pressure is high enough  
        println!("Unmapping {}MB",   // log it for debugging  
                 self.size / 1_048_576);  // convert bytes to MB  
        // mmap unmaps itself when dropped  
    }  
}

Enter fullscreen mode Exit fullscreen mode

Memory-mapped regions were our biggest leak source in Go. Here’s why: the Go GC looks at heap pressure. But mmapped memory isn’t on the heap — it’s virtual address space. So the GC would think “we have 10GB free on the heap, no need to collect!” while our virtual memory usage climbed to 18GB and the OOM killer was warming up.

With Drop, every mmap had a guaranteed munmap. Our virtual memory usage stabilized at 4.2GB instead of playing memory chicken with the kernel.

Simplified resource management through deterministic cleanup — fewer steps, predictable behavior, and guaranteed resource reclamation.

The Performance Cascade (Unexpected Bonuses)

Here’s what’s wild — deterministic cleanup created performance improvements we didn’t even anticipate:

1. Predictable Latency (The Big Surprise)

Our P99 latency dropped from 847ms to 34ms. But that’s not even the crazy part. The entire distribution tightened. Standard deviation went from 203ms to 8ms.

No more GC pauses. No more “well, sometimes it’s fast…” conversations with product managers.

2. Better Resource Utilization (Finally Using What We Paid For)

We reduced pod count from 42 to 11. Forty-two to eleven. Because with predictable memory usage, we didn’t need headroom for “what if the GC doesn’t run” scenarios.

CPU utilization increased from 38% to 67%. We were actually using the resources we paid for instead of keeping them idle for hypothetical GC spikes.

3. Simplified Monitoring (My Favorite Part)

Our alerting rules became trivial.

Before: “Alert if memory trend suggests OOM in 20 minutes based on polynomial regression of the last 6 data points weighted by time of day and…”

After: “Alert if memory exceeds 4GB.”

That’s it. One line. The predictability eliminated an entire category of complex anomaly detection that we’d spent months tuning.

The Real Cost (Let’s Be Honest)

Deterministic cleanup isn’t free. Nothing’s free. Here’s what we gave up:

What we lost:

  • Developer ergonomics (lifetime annotations everywhere in complex scenarios)
  • Rapid prototyping (steeper learning curve, especially for junior engineers)
  • Dynamic flexibility (can’t just hold references past scope without Arc/Rc)
  • Legacy integration (we rewrote 47,000 lines of Go over 4 months)

What we gained:

  • Zero memory leaks (from 47 incidents/month to 0 — ZERO)
  • Predictable performance (eliminated those 200+ms GC pauses)
  • Lower costs ($61,000/month savings, that’s real money)
  • Engineer confidence (no more 3am pages about memory)

The team adjustment was real. Three engineers needed 6 weeks to become productive with Rust’s ownership system. And I’m not gonna lie — those 6 weeks were rough. Lots of fighting with the borrow checker. Lots of “why can’t I just do this simple thing” moments.

But after that initial investment? Velocity increased. Features that previously required careful memory profiling and testing just… worked. First try. No leaks. No issues.

One engineer told me: “I used to spend 30% of my time tracking down memory issues. Now I spend 0%.”

When Should You Actually Do This?

After running this system for 14 months in production, here’s my decision framework:

Choose Rust’s Drop when:

  • Resource leaks cause production incidents (we had 10+ per month)
  • You’re managing system resources (files, sockets, memory-mapped regions)
  • Latency variance matters more than raw throughput (for us it did)
  • GC pauses disrupt critical paths (those 200ms pauses hurt)
  • Memory footprint directly impacts costs ($61K/month impact for us)
  • You need to know exactly when cleanup happens (not eventually)

Stay with GC languages when:

  • Development velocity is paramount (prototyping phase, MVP)
  • Resource leaks are acceptable edge cases (they’re not for everyone)
  • Team lacks systems programming experience (real consideration)
  • Cleanup timing doesn’t affect behavior (rare but it happens)
  • Memory is abundant and cheap (not our situation)
  • You can overprovision by 3–4x without caring (we couldn’t)

Eighteen Months Later

Our video service now processes 3.2 million files daily. That’s 33% growth. On the same infrastructure we were struggling with before.

Memory incidents in the past year: zero. Engineer time spent on memory issues: 4 hours total (mostly debugging one weird edge case). Infrastructure cost: still $22K/month instead of $83K.

The Drop trait didn’t just fix our memory leaks. It changed how we think about resources. Every struct becomes a contract: acquire on creation, cleanup on destruction. No timing uncertainty. No GC pressure. No praying to the runtime gods.

Just deterministic, predictable behavior.

I sleep through the night now. No memory-related pages. No panicked Slack messages at 2am. No watching graphs climb and hoping the GC runs before the OOM killer shows up.

The Real Lesson

Here’s what I learned: automatic cleanup isn’t always better than deterministic cleanup.

GC makes resource management invisible. Which is great! Until it’s not. Until you need to know when that file closes. Until you need to predict memory usage. Until you’re bleeding file descriptors and the GC is like “everything looks fine from here.”

Rust makes it explicit. Gives you control. You see exactly when cleanup happens because it’s tied to scope. No magic. No runtime surprises.

Our infrastructure costs dropped by $61,000 per month. But you know what? The real win was sleeping through the night. The real win was junior engineers shipping features without creating memory leaks. The real win was predictability.

Sometimes the best optimization is knowing exactly when your resources are freed.

Not “eventually.”

Now.


Enjoyed the read? Let’s stay connected!

🚀 Follow The Speed Engineer for more Rust, Go and high-performance engineering stories.

💡 Like this article? Follow for daily speed-engineering benchmarks and tactics.

⚡ Stay ahead in Rust and Go — follow for a fresh article every morning & night.

Your support means the world and helps me create more content you’ll love. ❤️