🚀 Executive Summary
TL;DR: Manually checking Netlify bandwidth is reactive and risks overage charges; this solution automates the process. A Python script fetches Netlify bandwidth data, calculates usage, and sends proactive Slack alerts when a configurable threshold is exceeded, preventing unexpected bills.
🎯 Key Takeaways
- Generate a Netlify Personal Access Token from User settings > Applications for API authentication.
- Set up a Slack Incoming Webhook to receive automated bandwidth alerts in a designated channel.
- Utilize `python-dotenv` to securely manage environment variables like `NETLIFY_API_TOKEN`, `SLACK_WEBHOOK_URL`, and `NETLIFY_TEAM_ID` in a `config.env` file.
- The Python script queries the Netlify API’s bandwidth endpoint (`/api/v1/{NETLIFY_TEAM_ID}/bandwidth`) to retrieve `used` and `included` bandwidth data.
- Configure an `ALERT_THRESHOLD_PERCENT` (e.g., 0.85) to trigger Slack notifications proactively before hitting the Netlify bandwidth cap.
- Automate the script’s execution using a cron job (e.g., weekly) to ensure continuous monitoring and timely alerts.
Monitor Netlify Bandwidth Usage and Alert before Cap
Alright, let’s talk about something that used to be a real time-sink for me: manually checking Netlify bandwidth. Before I automated this, I’d spend a good chunk of my Monday morning just logging into each account, pulling up the usage stats, and praying we weren’t about to hit a cap on a high-traffic site. It was tedious and reactive. This little Python script I’m about to show you turned that chore into a proactive, set-and-forget alert system. It saved me hours and, more importantly, a few near-misses on overage charges.
Prerequisites
Before we dive in, make sure you have the following ready:
- Python 3 installed on the machine that will run the script.
- A Netlify account with API access.
- Your Netlify Team ID (also known as the “account slug”).
- A Slack Workspace where you have permission to add an Incoming Webhook.
The Guide: Step-by-Step
Step 1: Get Your Netlify Personal Access Token
First, we need to authenticate with the Netlify API.
- Log in to your Netlify account.
- Click on your user avatar in the top-right corner and go to User settings.
- In the left-hand navigation, select Applications.
- Under “Personal access tokens,” click New access token.
- Give it a descriptive name like “Bandwidth Monitor” and generate the token.
- Important: Copy this token immediately and store it somewhere safe. You won’t be able to see it again.
Step 2: Create a Slack Incoming Webhook
Next, we need a way for our script to post messages to Slack.
- Navigate to the Slack API Apps page and click Create New App.
- Choose “From scratch,” give it a name (e.g., “Netlify Alerter”), and select your workspace.
- From the app’s settings page, select Incoming Webhooks and activate it.
- Click Add New Webhook to Workspace at the bottom.
- Choose the channel you want the alerts to be posted to (e.g., #devops-alerts) and click Allow.
- You’ll be given a Webhook URL. Copy it—this is another secret we’ll need.
Step 3: The Python Script
Now for the core logic. I’ll skip the standard project setup since you likely have your own workflow for that. Just create a directory for this project. You’ll need to install a couple of Python libraries; specifically, requests for making HTTP calls and python-dotenv for managing our secrets. You can generally install these using pip.
Inside your project directory, create a file named config.env. This is where we’ll store our secrets so they aren’t hardcoded in the script.
# config.env
NETLIFY_API_TOKEN="your_netlify_api_token_here"
SLACK_WEBHOOK_URL="your_slack_webhook_url_here"
NETLIFY_TEAM_ID="your_netlify_team_id_here"
Next, create the main Python script, let’s call it check_bandwidth.py.
# check_bandwidth.py
import os
import requests
from dotenv import load_dotenv
from datetime import datetime
# --- Configuration ---
# Load environment variables from config.env file
load_dotenv()
# Get secrets from environment
NETLIFY_API_TOKEN = os.getenv("NETLIFY_API_TOKEN")
SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
NETLIFY_TEAM_ID = os.getenv("NETLIFY_TEAM_ID")
# --- Thresholds ---
# Alert when usage exceeds 85% of the included bandwidth
ALERT_THRESHOLD_PERCENT = 0.85
# --- API Endpoints ---
NETLIFY_API_URL = f"https://api.netlify.com/api/v1/{NETLIFY_TEAM_ID}/bandwidth"
def get_netlify_bandwidth():
"""Fetches bandwidth data from the Netlify API."""
headers = {
"Authorization": f"Bearer {NETLIFY_API_TOKEN}"
}
try:
response = requests.get(NETLIFY_API_URL, headers=headers)
response.raise_for_status() # This will raise an exception for 4xx/5xx errors
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching data from Netlify API: {e}")
return None
def send_slack_alert(message):
"""Sends a formatted message to a Slack channel via webhook."""
payload = {"text": message}
try:
response = requests.post(SLACK_WEBHOOK_URL, json=payload)
response.raise_for_status()
print("Slack alert sent successfully!")
except requests.exceptions.RequestException as e:
print(f"Error sending Slack alert: {e}")
return
def main():
"""Main function to check bandwidth and send alerts."""
print("Running Netlify bandwidth check...")
if not all([NETLIFY_API_TOKEN, SLACK_WEBHOOK_URL, NETLIFY_TEAM_ID]):
print("Error: One or more environment variables are not set. Check your config.env file.")
return
data = get_netlify_bandwidth()
if not data:
print("Could not retrieve bandwidth data. Exiting.")
return
# Extract relevant data points
used_gb = data.get("used", 0) / (1024**3)
included_gb = data.get("included", 0) / (1024**3)
# Netlify API might return 0 if there's no limit, so handle that case
if included_gb == 0:
print("No included bandwidth limit found. Cannot calculate usage percentage.")
return
usage_percent = used_gb / included_gb
current_period_start = datetime.fromtimestamp(data.get("period_start_date", 0)).strftime('%Y-%m-%d')
current_period_end = datetime.fromtimestamp(data.get("period_end_date", 0)).strftime('%Y-%m-%d')
print(f"Current period: {current_period_start} to {current_period_end}")
print(f"Usage: {used_gb:.2f} GB / {included_gb:.2f} GB ({usage_percent:.2%})")
if usage_percent > ALERT_THRESHOLD_PERCENT:
alert_message = (
f":warning: *High Netlify Bandwidth Alert*\n\n"
f"Bandwidth usage is at *{usage_percent:.2%}* for the current billing period.\n"
f"> *Used:* {used_gb:.2f} GB\n"
f"> *Included:* {included_gb:.2f} GB\n"
f"> *Billing Period:* {current_period_start} to {current_period_end}\n\n"
f"Please review usage to avoid potential overages."
)
send_slack_alert(alert_message)
else:
print("Usage is within the threshold. No alert sent.")
if __name__ == "__main__":
main()
Pro Tip: I set my
ALERT_THRESHOLD_PERCENTto0.85(85%). This gives the team a comfortable buffer to investigate traffic spikes or plan an upgrade without the panic of hitting the hard cap. Don’t set it to 99%—that’s just asking for trouble.
Step 4: Automate with a Cron Job
The final piece is to make this script run on a schedule. On a Linux-based server, a cron job is the perfect tool for this. We can set it to run once a week, for example.
To edit your cron jobs, you’d typically use a command to open the crontab file. Inside, add a line like this to run the script every Monday at 2:00 AM. Make sure you are in the directory of your script before the command runs.
# Run the Netlify bandwidth check every Monday at 2 AM
0 2 * * 1 cd /path/to/your/project && python3 check_bandwidth.py >> /path/to/your/project/cron.log 2>&1
Remember to replace /path/to/your/project with the actual path to your script’s directory. Redirecting the output to a log file is a best practice for debugging.
Common Pitfalls (Where I Usually Mess Up)
-
Wrong IDs: Netlify has Site IDs, Team IDs, Account IDs… it’s easy to mix them up. For this bandwidth endpoint, you need the Team ID, which is often the “slug” or name you see in your Netlify team URL (e.g.,
app.netlify.com/teams/your-team-id/). -
Cron Environment Issues: A script that runs perfectly when you execute it manually might fail as a cron job. This is usually because the cron environment is minimal. It doesn’t know about your user’s PATH or where the
config.envfile is. Using thecdcommand in the cron line, as shown above, is a simple way to ensure the script runs from the correct directory. - API Rate Limits: My script runs once a week, which is perfectly fine. Don’t set your cron job to run every minute. You’ll likely hit API rate limits and get your access temporarily blocked. Once a day or a few times a week is more than enough for bandwidth monitoring.
Conclusion
And that’s it! You now have a simple, robust system to keep an eye on your Netlify bandwidth. It’s a small investment of time that pays off big in peace of mind and preventing unexpected bills or service interruptions. This frees you up to focus on what really matters: building and shipping great projects.
🤖 Frequently Asked Questions
âť“ How can I monitor Netlify bandwidth usage programmatically?
You can monitor Netlify bandwidth usage programmatically by using a Python script that authenticates with a Netlify Personal Access Token, queries the Netlify API’s bandwidth endpoint for your Team ID, and processes the returned `used` and `included` data.
âť“ How does this automated monitoring solution compare to Netlify’s built-in dashboard?
While Netlify’s dashboard provides usage visibility, this automated solution offers proactive, threshold-based alerts directly to Slack, eliminating manual checks and providing a buffer to prevent unexpected overage charges, which the dashboard alone does not do.
âť“ What is a common implementation pitfall when setting up the cron job?
A common pitfall is cron environment issues, where the script fails due to a minimal cron environment not finding `config.env` or required executables. This is solved by using `cd /path/to/your/project && python3 check_bandwidth.py` in the cron line to ensure the script runs from the correct directory with the proper context.
Leave a Reply