如何为云资源设置预算告警?
解读
在国内云厂商(阿里云、腾讯云、华为云)的面试里,这道题表面问“预算告警”,实则考察候选人是否具备“用代码把财务风险变成技术事件”的能力。
FastAPI 作为微服务网关,常承担“统一收口”角色:
- 它要能把云账单数据拉回来(异步爬虫/云 SDK);
- 要能把阈值规则跑起来(定时任务或事件驱动);
- 要能把告警发出去(企业微信、飞书、钉钉、短信、邮件);
- 还要让这一切可灰度、可回滚、可审计。
因此,面试官想听到的是:你如何用 FastAPI 把“预算告警”做成一个可插拔、可观测、可水平扩展的 Python 服务,而不是简单地在控制台里点两下。
知识点
- 云账单获取
- 阿里云:BSS OpenAPI → QueryAccountBill、DescribeInstanceBill;
- 腾讯云:Billing API → DescribeBillResourceDetail;
- 统一用异步 SDK(alibabacloud-bss20171214、TencentCloud SDK)+ httpx.AsyncClient 做并发限流。
- 额度模型设计
- 预算维度:账号、地域、产品、标签、项目(ResourceGroup);
- 周期:日、周、月、季度;
- 阈值类型:固定值、环比增长率、机器学习基线;
- 分级:预警(80%)、告警(100%)、熔断(120%)。
- 规则引擎
- 用 Pydantic 做强类型校验,FastAPI Depends 注入;
- 规则存 MySQL/PostgreSQL,或 etcd 做热更新;
- 异步任务用 BackgroundTasks、Celery、arq 或 FastAPI-Scheduler。
- 告警通道
- 钉钉:加签机器人,支持 @全体;
- 飞书:富文本卡片 + 交互按钮“立即关机”;
- 短信:阿里云 SMS、腾讯云 SMS,需做运营商内容审核;
- 邮件:Jinja2 模板渲染,附件带 CSV 账单。
- 可观测
- Prometheus:自定义指标 budget_consumption_ratio、budget_alert_total;
- Grafana:大盘按账号/产品聚合;
- OpenTelemetry:链路追踪到每条云 API 调用;
- Sentry:捕获 SDK 限流、JSON 解析异常。
- 安全合规
- RAM/STS 最小权限:只读账单权限,禁止资源操作;
- 敏感字段(手机号、邮箱)脱敏落库;
- 审计日志:谁改了阈值、谁点了忽略告警,落 ELK 并保存 180 天;
- 国密 SM4 加密数据库字段,满足等保 2.0。
- 高可用
- 无状态容器化,K8s HPA 按 CPU 50% 伸缩;
- 拉账单任务分片,用 Redis 分布式锁防重复;
- 多区域部署,告警通道走双云互备(钉钉+飞书)。
答案
下面给出一个可直接落地的 FastAPI 服务骨架,演示“为阿里云账号设置月度预算告警”的最小闭环。
目录结构
budget_alert/
├── main.py
├── models.py
├── schemas.py
├── deps.py
├── crud.py
├── aliyun_bill.py
├── notifier.py
└── tasks.py
-
环境变量
export ALIYUN_ACCESS_KEY_ID=LTAI5txxx
export ALIYUN_ACCESS_KEY_SECRET=xxx
export DINGTALK_WEBHOOK=https://oapi.dingtalk.com/robot/send?access_token=xxx
export DINGTALK_SECRET=SECxxx -
schemas.py
from pydantic import BaseModel, condecimal
from datetime import date
class BudgetSchema(BaseModel):
account_id: str
dimension: str = "Total" # Total | ECS | RDS ...
cycle: str = "Monthly" # Daily | Monthly
threshold: condecimal(gt=0, decimal_places=2)
alert_percent: condecimal(ge=0, le=100, decimal_places=2) = 80
class AlertOut(BaseModel):
account_id: str
dimension: str
usage: float
threshold: float
ratio: float
message: str
- models.py(SQLAlchemy)
from sqlalchemy import Column, String, Numeric, DateTime, Boolean
from db import Base
class Budget(Base):
__tablename__ = "budgets"
id = Column(String(64), primary_key=True, comment="account_id#dimension#cycle")
threshold = Column(Numeric(12, 2), nullable=False)
alert_percent = Column(Numeric(5, 2), default=80)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
- aliyun_bill.py(异步拉账单)
import httpx
from datetime import datetime
from alibabacloud_bss20171214.client import Client
from alibabacloud_tea_openapi.models import Config
async def fetch_month_bill(account_id: str, month: str) -> float:
cfg = Config(
access_key_id=os.getenv("ALIYUN_ACCESS_KEY_ID"),
access_key_secret=os.getenv("ALIYUN_ACCESS_KEY_SECRET"),
endpoint="business.aliyuncs.com"
)
client = Client(cfg)
resp = await client.query_account_bill_async(
billingCycle=month,
type="Usage"
)
total = sum(float row["OutstandingAmount"]) for row in resp.body.data.items.item)
return total
- notifier.py(钉钉群机器人)
import hmac, time, base64, hashlib, httpx
async def send_dingtalk(msg: str):
timestamp = str(round(time.time() * 1000))
secret = os.getenv("DINGTALK_SECRET")
webhook = os.getenv("DINGTALK_WEBHOOK")
sign = base64.b64encode(
hmac.new(
secret.encode(),
f"{timestamp}\n{secret}".encode(),
digestmod=hashlib.sha256
).digest()
).decode()
url = f"{webhook}×tamp={timestamp}&sign={sign}"
await httpx.AsyncClient().post(url, json={"msgtype": "text", "text": {"content": msg}})
- tasks.py(定时检查)
from apscheduler.schedulers.asyncio import AsyncIOScheduler
sched = AsyncIOScheduler()
@sched.scheduled_job("cron", hour="1", minute="0") # 每天 01:00 跑
async def check_budget():
from crud import list_budgets
for budget in await list_budgets():
month = datetime.now().strftime("%Y-%m")
usage = await fetch_month_bill(budget.account_id, month)
ratio = usage / float(budget.threshold) * 100
if ratio >= float(budget.alert_percent):
msg = f"【预算告警】账号 {budget.account_id} 本月已使用 {usage:.2f} 元,达到预算 {budget.threshold} 元的 {ratio:.1f}%"
await send_dingtalk(msg)
- main.py(FastAPI 入口)
from fastapi import FastAPI
from tasks import sched
import notifier, aliyun_bill # 提前注册
app = FastAPI(title="云预算告警中心", version="1.0.0")
@app.on_event("startup")
async def start():
sched.start()
@app.on_event("shutdown")
async def stop():
sched.shutdown()
@app.post("/budget", response_model=schemas.AlertOut)
async def create_budget(budget: schemas.BudgetSchema):
await crud.upsert_budget(budget)
return {"message": "budget saved"}
- 部署
- Dockerfile:多阶段构建,python:3.11-slim,非 root 用户;
- K8s:CronJob 做兜底,Deployment 跑主服务;
- 配置中心:Nacos/Apollo 热更新阈值;
- 灰度:在预算 id 上加 label,飞书先灰度 5% 账号。
至此,一个基于 FastAPI 的“云资源预算告警”微服务就完成了:自动拉账单、规则可配、告警可达、可观测、可灰度,完全符合国内云原生场景。
拓展思考
- 多云场景
把阿里云、腾讯云、华为云、AWS 中国账单统一抽象成 BillingProvider 接口,用策略模式动态路由,FastAPI 后台只需一份阈值规则。 - 实时流式
云厂商支持“账单推送”事件(阿里云 MNS、腾讯云 CMQ),用 FastAPI + Starlette WebSocket 把大额消费推送到前端大屏,实现秒级告警。 - 智能预测
用 Prophet 或 ARIMA 训练历史账单,FastAPI 提供 /forecast 接口,提前 7 天预测是否超预算,把“事后告警”变成“事前干预”。 - 自动熔断
当预算达到 120% 时,调用云 API 关停指定标签下的按量实例,FastAPI 作为熔断网关,需做二次确认+审批流,防止误杀核心服务。 - 合规审计
引入国密 SM2 签名+时间戳,保证“阈值修改”操作不可抵赖;FastAPI 中间件自动为每次写操作生成审计事件,推送到区块链存证平台,满足金融级合规要求。