Skip to content
~/writing
.NETInfrastructure

Defending a .NET API against DDoS attacks

/ 3 min read / Ejan Shrestha

A DDoS attack (Distributed Denial of Service) is a malicious attempt to disrupt the normal traffic of a targeted server, service, or network by overwhelming it with a flood of internet traffic.


🔍 How It Works:

  • Distributed: The attack comes from many different sources, often from a network of infected computers (called a botnet).

  • Denial of Service: The target becomes unavailable to legitimate users because it's overloaded with fake traffic.


💥 Common Types of DDoS Attacks:

  1. Volume-Based Attacks

    • Goal: Consume all available bandwidth.

    • Example: UDP floods, ICMP floods.

    • Measured in: Gbps (Gigabits per second)

  2. Protocol Attacks

    • Goal: Exploit weaknesses in Layer 3 and 4 protocols (e.g., TCP/IP).

    • Example: SYN flood, Ping of Death.

    • Measured in: Packets per second (PPS)

  3. Application Layer Attacks

    • Goal: Target Layer 7 (HTTP/HTTPS) where web pages are generated.

    • Example: HTTP flood, Slowloris.

    • Measured in: Requests per second (RPS)


⚠️ Real-World Consequences:

  • Downtime for websites or apps.

  • Loss of revenue and reputation.

  • Security teams may miss other intrusions while dealing with the flood.


🛡️ Prevention & Mitigation:

  • Use Web Application Firewalls (WAF).

  • Employ rate limiting and traffic filtering.

  • Partner with CDNs or DDoS protection services like Cloudflare or AWS Shield.

  • Monitor traffic for abnormal patterns.


Let me know if you want a diagram or code-level example related to .NET or networking security practices for handling DDoS threats.

✅ Diagram: What a DDoS Attack Looks Like

Here's a basic representation:

  [Bot 1]         [Bot 2]         [Bot 3]         [Bot N]
     |               |               |               |
     +---------------+---------------+---------------+
                                 ↓
                    [Your .NET API Server (Target)]
                          ↑         ↑
                    Legitimate users get denied

🧰 Step-by-Step Mitigation in .NET Web API

While you can’t stop a full-scale DDoS (especially at the infrastructure level) from code alone, you can reduce the impact with smart coding and proper configurations.


🔐 1. Rate Limiting

Use a middleware like AspNetCoreRateLimit.

🛠️ Setup:

Install via NuGet:

dotnet add package AspNetCoreRateLimit

Configure in Program.cs:

builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
 
app.UseIpRateLimiting();

Add to appsettings.json:

"IpRateLimiting": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIpHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "GeneralRules": [
    {
      "Endpoint": "*",
      "Period": "1s",
      "Limit": 5
    },
    {
      "Endpoint": "*",
      "Period": "1m",
      "Limit": 100
    }
  ]
}

🛡️ 2. Throttle Resource-Intensive Endpoints

Limit or defer heavy operations like report generation, file uploads, or PDF creation:

[HttpPost]
[Route("generate-heavy-report")]
public async Task<IActionResult> GenerateReport(CancellationToken token)
{
    if (!IsRequestAllowed(Request))
        return StatusCode(429, "Too Many Requests");
 
    var report = await _reportService.GenerateAsync(token);
    return File(report, "application/pdf");
}

🔍 3. Use Application Firewall / CDN

Offload protection to services before requests reach your .NET server:

  • 🛡️ Cloudflare, AWS Shield, or Azure Front Door

  • 🌐 Reverse proxy (e.g., NGINX or Azure Application Gateway)


🧪 4. Detect Patterns via Logs

Use structured logging (e.g., Serilog + Seq) to identify high-frequency IPs.

Log.Information("Request from IP: {IP}", HttpContext.Connection.RemoteIpAddress);

Later, you can aggregate and analyze in a dashboard like Kibana, Grafana, or Seq.


🧰 5. Caching to Reduce Repeated Computation

Use MemoryCache or ResponseCache for GET endpoints:

[HttpGet]
[ResponseCache(Duration = 60)]
public IActionResult GetPublicData()
{
    var data = _service.GetCachedData();
    return Ok(data);
}

⚙️ 6. Enable Connection Limits (Infrastructure Level)

On IIS / Kestrel / nginx, configure:

  • Max connections

  • Max requests per second

  • Timeouts

For Kestrel, in appsettings.json:

"Kestrel": {
  "Limits": {
    "MaxConcurrentConnections": 100,
    "MaxRequestBodySize": 10485760
  }
}

📦 Optional: Cloudflare DDoS Protection

If you're hosting the API behind a domain, you can enable Cloudflare’s DDoS protection in their dashboard, which will:

  • Filter malicious traffic.

  • Challenge bots.

  • Log/report events.


✅ Summary Checklist

DefenseLevelTool
Rate LimitingAppAspNetCoreRateLimit
Firewall RulesInfraIIS / Azure / Cloudflare
CachingAppResponseCache, IMemoryCache
Logging & DetectionAppSerilog + Seq
CDN + Edge ProtectionEdgeCloudflare / Azure Front Door
AlertingMonitoringApplication Insights / Prometheus

Ejan Shresthaइजन श्रेष्ठ

Senior Software Engineer, backend and .NET modernisation

Senior software engineer in Kathmandu with 4+ years shipping .NET for insurance and enterprise. I own reliability and modernisation for an insurance platform of 50 .NET projects on Kubernetes: structured logging and tracing across old and new services, the plan off end-of-life .NET to .NET 10, and the fix for socket exhaustion across ~390 call sites.

Selected impact

  • ~390Ending socket exhaustion across the platform. The error class disappeared from production logs, and outbound HTTP now has one place for retries and tracing.
  • 1 IDOne trace from gateway to database. One correlation ID now follows a request end to end.
  • 61%From end-of-life .NET to .NET 10. A sequenced roadmap with known risks; the first services already run on .NET 10.
  • v16A public website on Next.js 16. Shipped to production with a tested rollback path.
  • 4A release standard people follow. Releases are predictable enough to schedule.

Experience

  1. Senior Software Engineer, Himalayan Everest Insurance

    Jan 2025 – present

    Kathmandu, hybrid

    • Own backend reliability and modernisation for an insurance platform of 50 .NET projects, deployed as 28 Kubernetes workloads, across accounting, claims, reinsurance and reporting.
    • Leading the upgrade from .NET Core 2.2, 3.1 and 5 to .NET 10, including the IdentityServer4 replacement.
    • Built structured logging and tracing across every service.
    • Upgraded the public website and CMS to Next.js 16, React 19, Strapi 5 and Node 24.
  2. .NET Developer, EKbana Solutions

    Jul 2022 – Nov 2024

    Lalitpur, on-site

    • Designed backend services for enterprise insurance workflows with ASP.NET Core, PostgreSQL, EF Core and Dapper.
    • Built REST APIs and integrations for customer portals, payments and external partners.
    • Ran background workflows on Hangfire with idempotency, retries and failure recovery.
    • Shipped on Docker, Linux, Nginx/Traefik and Kubernetes; worked on IdentityServer, JWT and RBAC.
  3. Dotnet Developer, NBIT

    Jan 2022 – Jun 2022

    Lalitpur

    • Built and maintained .NET Framework applications for client projects.
  4. Data Specialist, CloudFactory

    Nov 2017 – Jun 2022

    Kathmandu

    • Delivered high-accuracy data work for international clients while completing my degree.