View : 0

04/03/2026 08:46am

EP.87 DDoS Protection for WebSocket Server

EP.87 DDoS Protection for WebSocket Server

#security

#DDoS

#WebSocket

#Golang

#Go

WebSocket servers are at the heart of real-time applications — from chat systems and online games to live notifications. But once your system goes public and begins accepting large-scale traffic, it becomes vulnerable to attacks such as:

  • DDoS (Distributed Denial-of-Service)
  • Connection Flood
  • Malformed Frame Attacks

This article walks you through essential techniques to secure your WebSocket server and prepare it for real-world production use. 🌐

 

☠️ Common Types of WebSocket Attacks

 

Attack TypeDescription
DDoS (Distributed Denial-of-Service)Overwhelming the server with a high volume of requests from multiple sources to cause failure
Connection FloodExcessive WebSocket connections from a single or multiple IPs to exhaust server resources
Malformed Frame AttackSending invalid WebSocket frames to crash or freeze the server

 

🔒 How to Protect Your WebSocket Server

 

1. Limit Connections per IP

Use rate limiting or connection throttling to prevent any single client from creating excessive connections.

 

✅ Example Go Code (Fiber + WebSocket):

package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/websocket/v2"
    "sync"
)

var connections = make(map[string]int)
var mu sync.Mutex
const maxConnectionsPerIP = 5

func main() {
    app := fiber.New()

    app.Get("/ws", websocket.New(func(c *websocket.Conn) {
        ip := c.RemoteAddr().String()
        mu.Lock()
        connections[ip]++
        if connections[ip] > maxConnectionsPerIP {
            mu.Unlock()
            c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "Too many connections"))
            c.Close()
            return
        }
        mu.Unlock()

        defer func() {
            mu.Lock()
            connections[ip]--
            mu.Unlock()
            c.Close()
        }()

        for {
            _, msg, err := c.ReadMessage()
            if err != nil {
                break
            }
            c.WriteMessage(websocket.TextMessage, msg)
        }
    }))

    app.Listen(":8080")
}

 

🔍 Explanation:
We track the number of active connections per IP using a map. If a client exceeds the allowed threshold, the server terminates the connection immediately.

 

2. Detect Malformed Frames

Your WebSocket code should be ready to catch invalid frames and handle them gracefully to avoid crashes or hangs.

 

✅ Example Code:

for {
    messageType, msg, err := c.ReadMessage()
    if err != nil {
        if websocket.IsCloseError(err, websocket.CloseProtocolError) {
            fmt.Println("Malformed frame detected from:", c.RemoteAddr())
        }
        break
    }
    fmt.Println("Received message:", string(msg))
    c.WriteMessage(messageType, msg)
}

 

🔍 Explanation:
Use IsCloseError to detect protocol-level errors caused by malformed frames, then log or take necessary action.

 

3. Use Firewall or Reverse Proxy for Network-Level Defense

Besides coding safeguards, it’s crucial to deploy edge-layer protection using tools like:

ToolUse Case
NGINX / CloudflareRate limiting, IP blacklisting, DoS protection
iptablesLimiting number of connections per IP
Cloud-based WAFDDoS protection with WebSocket support

 

✅ NGINX Configuration Example:

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    listen 80;

    location /ws {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        limit_conn addr 5; # limit connections per IP
    }
}

 


 

🧠 Summary: What You've Learned

 

  • WebSocket servers are vulnerable to DDoS, flooding, and malformed traffic.
  • Limit the number of concurrent connections per IP using Go code.
  • Detect and handle malformed frames using standard error-checking methods.
  • Add firewall or reverse proxy layers to filter malicious traffic.

✅ When you combine code-level protection with infrastructure-level safeguards, your WebSocket server will be ready for production — secure, scalable, and resilient.

 

🚀 Challenge for You

 

  • Run a WebSocket server with IP-based connection limits.
  • Simulate malformed frames and see how the system reacts.
  • Deploy behind Cloudflare and test with aggressive traffic to validate protection.

 

🔜 Coming Up Next

 

EP.88: Building Multi-Room Chat Management in Go

Learn how to implement scalable chat rooms with separate user groups, real-time message broadcasting, and clean separation of communication channels!

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en