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

推荐订阅源

G
Google Developers Blog
阮一峰的网络日志
阮一峰的网络日志
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
V
Visual Studio Blog
Martin Fowler
Martin Fowler
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
I
InfoQ
B
Blog RSS Feed
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
IT之家
IT之家
P
Proofpoint News Feed
WordPress大学
WordPress大学
小众软件
小众软件
B
Blog
MongoDB | Blog
MongoDB | Blog
人人都是产品经理
人人都是产品经理
量子位
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客

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 Silent Crash: Handling Zombie WebSockets in Python Io...
Bisal · 2026-06-25 · via DEV Community

Bisal

One harsh truth we discover while building backend systems for IoT devices like industrial sensors or electric vehicle (EV) chargers is this: Hardware lies. Your Python WebSocket server works flawlessly on your local machine, but deploy it to production where physical hardware is shoved into underground concrete parking garages, fighting high-voltage electromagnetic interference, and constantly falling back to legacy 2G/3G networks, and your server will quickly fall victim to "Zombie Connections."

I still remember a seminar I attended where a gentleman was explaining how he had deployed their IoT devices on generators in remote mining locations. They were facing this exact issue. The IoT devices were sending all-green signals, but the physical generators were completely offline.

A Zombie Connection happens when an IoT device loses cellular service and drops off the network abruptly, failing to send a standard TCP close frame. The Python server still considers it an open connection.

The Naive (and Dangerous) Approach
Most Python WebSocket tutorials teach you to handle connections like this:

Python
import asyncio
import websockets

async def handle_connection(websocket):
    while True:
        # DANGER: This line blocks forever if the connection drops silently
        data = await websocket.recv() 
        await process_sensor_data(data)

In an IoT application, this code is a ticking time bomb. If 1000 devices drive into tunnels and lose signal silently, you now have 1000 coroutines permanently suspended in your asyncio event loop waiting for data that will never arrive. Eventually, your server runs out of file descriptors or memory, and crashes.

The Fix: Aggressive Heartbeats and Timeouts
To build a fault-tolerant ingestion layer, we must stop trusting the socket state and actively interrogate the connection using asyncio.wait_for and WebSocket Ping/Pong frames.
Here is how you write a non-blocking connection handler:

Python
import asyncio
import websockets

async def process_sensor_data(data):
    # Your business logic goes here
    pass

async def handle_connection(websocket):
    try:
        while True:
            try:
                # 1. Wait for data, but strictly timeout after 30 seconds
                data = await asyncio.wait_for(websocket.recv(), timeout=30.0)
                await process_sensor_data(data)

            except asyncio.TimeoutError:
                # 2. No data received in 30s. The device might be dead, or just idle.
                # We actively send a ping to find out.
                pong_waiter = await websocket.ping()

                try:
                    # Wait 10 seconds for the hardware to reply to the ping
                    await asyncio.wait_for(pong_waiter, timeout=10.0)
                except asyncio.TimeoutError:
                    # 3. No pong received. It's a Zombie. Kill it.
                    print(f"Zombie connection detected. Freeing server resources.")
                    await websocket.close()
                    break # Exit the loop and destroy the coroutine

    except websockets.exceptions.ConnectionClosed:
        print("Connection closed cleanly by the hardware.")

Why This Architecture Wins
By wrapping our asynchronous receives in strict timeouts, we take back control of the event loop. We allow the server to gracefully reap dead connections, free up memory, and prepare for the hardware to eventually regain cellular service and reconnect.

Remember, there are a lot of zombie "connections" out there :)