Last active
August 20, 2024 15:47
-
-
Save jkoop/b1ce00c6a0478eca7337db23fd9f5750 to your computer and use it in GitHub Desktop.
A Laravel Middleware that checks the system's current 15 minute loadavg and the number of CPUs, and if the resulting division is greater than 85%, returns 503 with an appropriate message.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{-- resources/views/errors/overloaded.blade.php --}} | |
@extends('errors.layout') | |
@section('title', 'Server Overloaded') | |
@section('content') | |
<div class="flex items-center pt-8 sm:justify-start sm:pt-0" style="width: max-content"> | |
<div class="border-r border-gray-400 text-lg tracking-wider text-gray-500" style="padding-right: 20px"> | |
503 | |
</div> | |
<div class="text-lg uppercase tracking-wider text-gray-500" style="padding-left: 20px"> | |
Server Overloaded | |
</div> | |
</div> | |
<div class="text-gray-500" style="font-size: small; margin-top: 12px"> | |
Please wait a minute and try again. | |
</div> | |
@endsection |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// app/Http/Middleware/PreventOverloading.php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
/** | |
* A Laravel Middleware that checks the system's current 15 minute | |
* loadavg and the number of CPUs, and if the resulting division | |
* is greater than 85%, returns 503 with an appropriate message. | |
* | |
* @license MIT 2024 Joe Koop | |
*/ | |
class PreventOverloading { | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next | |
*/ | |
public function handle(Request $request, Closure $next): Response { | |
// 15 min average | |
$loadavg = `cat /proc/loadavg | awk '{print$3}'` / `cat /proc/cpuinfo | grep -E '^processor\s+:' | wc -l`; | |
if ($loadavg > 0.85) { | |
if ($request->acceptsHtml()) { | |
return response( | |
status: 503, | |
headers: ["Refresh" => 10, "Retry-After" => 10], | |
content: view("errors.overloaded"), | |
); | |
} | |
abort(503, "Server Overloaded", ["Retry-After" => 10]); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment