In this episode, we're diving into how to calculate the uptime percentage for each of our endpoints, which is a bit more involved than just counting successes and failures. We start by looking at a sample endpoint that has an even split of successful and unsuccessful checks, aiming to display its 50% uptime rate in the UI.
To achieve this, we create an uptimePercentage
method on our Endpoint model. The core idea is to compute the number of successful checks, divide by the total number of checks, and multiply by 100 to get the percentage. Instead of iterating through all checks in code, we leverage Laravel's ability to do this counting directly at the database level using withCount
—which is much more efficient.
We set up an aggregate so each endpoint is automatically returned with a successful_checks_count
, which tracks only the checks with HTTP status codes in the 200–299 range. This way, we can quickly access both the total check count and the count of successful ones.
After setting up the calculation, we touch on some common edge cases. For example, we handle endpoints with no checks by returning a dash (-
) instead of showing a misleading "0%" uptime. We also make sure to format the percentage to two decimal places for a cleaner display.
Finally, we do a quick recap about why counting at the database level is preferable here and point out a potential future performance issue (needing to eager load the counts). We'll tidy that up in a later video. For now, you'll see uptime percentages showing accurately and efficiently throughout your endpoint listings!