i have a server application that is increasingly frequently experiencing rudimentary denial-of-service attacks. the attacks often follow a similar progression:
a malicious actor makes a large number of requests at random, some of which hit very expensive endpoints, driving up CPU usage.
the application operates more-or-less normally for several hours as the attacker burns through flex quota.
the application exhausts its flex quota and shuts down.
is there a way for a swift application to monitor its own CPU usage, so it can detect when it has entered stage 2, and possibly slow itself down to prevent the situation from progressing to stage 3?
On Linux, reading and understanding
/proc/self/stat should do the trick. See eg, https://github.com/apple/swift-metrics-extras/tree/main/Sources/SystemMetrics
Do you see that the attack originates from the same ip address or ip address range? Many cloud providers offer sth like a „Web Application Firewall“ which can automatically block suspicious traffic (eg based on some rate limit per geographic region)
getrusage is a cross-platform (Darwin & Linux, at least) way to get basic resource usage information about ones own process (or potentially others, depending on the platform).
i’m kind of hesitant to add traffic filters at the cloud provider level, because the site in question is served over HTTPS, and there are many legitimate uses of the site that would appear like a large amount of requests originating from the same IP address, and i’m skeptical that it would be possible to flag traffic as suspicious without inspecting the requests themselves.