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.
Python code
11 linesbudget = 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
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
- Use a dataclass to encapsulate budget and threshold, and add a method for checking alerts.
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.