How to Build a Budget Alert Threshold with Mock Notifications in Python

This code calculates budget usage percentage and triggers a mock alert notification when the usage exceeds a defined threshold.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

11 lines
Python 3.9+
budget = 500.0
spent = 620.0
alert_threshold = 0.8

def mock_notify(percent_used):
    if percent_used >= alert_threshold:
        return f"ALERT: Budget usage at {percent_used * 100:.1f}% — over {alert_threshold * 100:.0f}% threshold!"
    return f"OK: Budget usage at {percent_used * 100:.1f}% — under threshold."

percent_used = spent / budget
print(mock_notify(percent_used))

Output

stdout
ALERT: Budget usage at 124.0% — over 80% threshold!

How it works

The code computes the percentage of budget spent by dividing spent by budget. The mock_notify function compares this percentage against a threshold (0.8, i.e., 80%). If the percentage is at or above the threshold, it returns an alert message; otherwise, it returns a status message. This pattern is useful for cost monitoring in cloud environments where you need to warn when spending approaches a limit. The threshold and budget values are constants, making the logic easy to adjust for different scenarios.

Common mistakes

  • Dividing budget by spent instead of spent by budget, which skews the usage ratio.
  • Hardcoding the threshold inside the function instead of using a configurable constant.
  • Forgetting to multiply by 100 when converting a ratio to a percentage for display.

Variations

  1. Use a dataclass to encapsulate budget and threshold, and add a method for checking alerts.
  2. Integrate with a real notification service like AWS SNS or Slack webhook in production.

Real-world use cases

  • Monitoring cloud spend per project and alerting when usage exceeds a monthly budget threshold.
  • Checking resource utilization (like CPU or memory) against allocated quotas in a scaling system.
  • Triggering a cost-control response when a CI pipeline spends beyond a set amount on cloud resources.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.