microwind/ai-skills/serverless-functions

Claude Code and agent skill by microwind/ai-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

当开发无服务器函数时,分析函数架构设计,优化冷启动性能,解决函数扩展问题。验证事件处理,设计微服务架构,和最佳实践。

Install

npx vskill@latest install microwind/ai-skills/serverless-functions

SKILL.md

The same SKILL.md was published earlier as microwind/ai-skills/serverless-functions.

无服务器函数技能

概述

无服务器函数是现代云原生应用的核心组件。不当的函数设计会导致冷启动延迟、资源浪费和性能问题。在设计无服务器架构前需要仔细分析业务需求。

核心原则: 好的无服务器函数应该快速启动、高效执行、自动扩展,同时保证成本可控。坏的函数设计会导致高延迟、高成本和维护困难。

何时使用

始终:

  • 设计事件驱动架构时
  • 实现微服务后端逻辑时
  • 处理异步任务和工作流时
  • 构建API网关和端点时
  • 优化云原生应用架构时

触发短语:

  • "无服务器函数设计"
  • "Lambda函数优化"
  • "冷启动问题解决"
  • "函数扩展策略"
  • "事件驱动架构"
  • "Serverless最佳实践"

无服务器函数功能

函数架构设计
  • 函数拆分策略
  • 事件源配置
  • 触发器设置
  • 错误处理机制
  • 状态管理方案
性能优化
  • 冷启动优化
  • 内存配置调优
  • 并发控制策略
  • 超时时间设置
  • 资源利用率分析
监控和调试
  • 函数执行监控
  • 性能指标收集
  • 错误日志分析
  • 调试工具配置
  • 告警规则设置
部署和管理
  • 函数版本管理
  • 环境配置管理
  • 自动化部署流程
  • 测试策略制定
  • 安全配置检查

常见无服务器函数问题

冷启动延迟
问题:
函数冷启动时间过长,影响用户体验
错误示例:
- 函数包体积过大
- 依赖库过多
- 初始化逻辑复杂
- 运行时选择不当
解决方案:
1. 优化函数包大小,移除不必要依赖
2. 使用预热策略保持函数活跃
3. 选择合适的运行时和内存配置
4. 简化初始化逻辑
内存和并发限制
问题:
函数内存不足或并发达到上限
错误示例:
- 内存配置过低
- 并发数设置不当
- 资源泄漏未处理
- 长时间运行任务
解决方案:
1. 根据实际需求调整内存配置
2. 设置合理的并发限制
3. 优化代码避免资源泄漏
4. 拆分长时间任务为多个函数
错误处理不当
问题:
函数错误处理机制不完善,导致任务失败
错误示例:
- 缺少异常捕获
- 重试策略不当
- 死信队列未配置
- 监控告警缺失
解决方案:
1. 完善异常处理和错误捕获
2. 配置合适的重试策略
3. 设置死信队列处理失败消息
4. 建立完善的监控告警

代码实现示例

无服务器函数分析器
python
import json
import time
import boto3
import zipfile
import os
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class FunctionMetrics:
"""函数指标"""
name: str
runtime: str
memory_size: int
timeout: int
code_size: int
cold_start_time: float
average_duration: float
error_rate: float
invocation_count: int
cost_per_month: float
@dataclass
class FunctionIssue:
"""函数问题"""
severity: str # critical, high, medium, low
type: str
function_name: str
message: str
suggestion: str
affected_metrics: List[str]
class ServerlessFunctionAnalyzer:
def __init__(self, region: str = 'us-east-1'):
self.region = region
self.lambda_client = boto3.client('lambda', region_name=region)
self.cloudwatch_client = boto3.client('cloudwatch', region_name=region)
self.issues: List[FunctionIssue] = []
def analyze_functions(self, function_names: List[str] = None) -> Dict[str, Any]:
"""分析Lambda函数"""
try:
if function_names is None:
# 获取所有函数
functions = self.lambda_client.list_functions()
function_names = [f['FunctionName'] for f in functions['Functions']]
function_metrics = []
for function_name in function_names:
metrics = self.analyze_function(function_name)
if metrics:
function_metrics.append(metrics)
# 生成分析报告
report = {
'total_functions': len(function_metrics),
'functions': [self.metrics_to_dict(m) for m in function_metrics],
'issues': self.issues,
'cost_analysis': self.analyze_costs(function_metrics),
'performance_analysis': self.analyze_performance(function_metrics),
'recommendations': self.generate_recommendations(function_metrics)
}
return report
except Exception as e:
return {'error': f'分析失败: {e}'}
def analyze_function(self, function_name: str) -> Optional[FunctionMetrics]:
"""分析单个函数"""
try:
# 获取函数配置
function_config = self.lambda_client.get_function_configuration(
FunctionName=function_name
)
# 获取函数统计信息
function_stats = self.get_function_statistics(function_name)
# 计算冷启动时间
cold_start_time = self.measure_cold_start_time(function_name)
# 分析函数代码
code_analysis = self.analyze_function_code(function_name)
# 计算月度成本
monthly_cost = self.calculate_monthly_cost(function_config, function_stats)
metrics = FunctionMetrics(
name=function_name,
runtime=function_config['Runtime'],
memory_size=function_config['MemorySize'],
timeout=function_config['Timeout'],
code_size=function_config['CodeSize'],
cold_start_time=cold_start_time,
average_duration=function_stats.get('average_duration', 0),
error_rate=function_stats.get('error_rate', 0),
invocation_count=function_stats.get('invocation_count', 0),
cost_per_month=monthly_cost
)
# 检查函数问题
self.check_function_issues(metrics, code_analysis)
return metrics
except Exception as e:
print(f'分析函数 {function_name} 失败: {e}')
return None
def get_function_statistics(self, function_name: str) -> Dict[str, float]:
"""获取函数统计信息"""
try:
# 获取过去30天的CloudWatch指标
end_time = time.time()
start_time = end_time - 30 * 24 * 60 * 60 # 30天前
# 获取平均执行时间
duration_response = self.cloudwatch_client.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Duration',
Dimensions=[{'Name': 'FunctionName', 'Value': function_name}],
StartTime=start_time,
EndTime=end_time,
Period=24 * 60 * 60, # 1天
Statistics=['Average']
)
# 获取错误率
errors_response = self.cloudwatch_client.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Errors',
Dimensions=[{'Name': 'FunctionName', 'Value': function_name}],
StartTime=start_time,
EndTime=end_time,
Period=24 * 60 * 60,
Statistics=['Sum']
)
# 获取调用次数
invocations_response = self.cloudwatch_client.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Invocations',
Dimensions=[{'Name': 'FunctionName', 'Value': function_name}],
StartTime=start_time,
EndTime=end_time,
Period=24 * 60 * 60,
Statistics=['Sum']
)
# 计算统计数据
avg_duration = 0
if duration_response['Datapoints']:
avg_duration = sum(d['Average'] for d in duration_response['Datapoints']) / len(duration_response['Datapoints'])
total_errors = sum(d['Sum'] for d in errors_response['Datapoints'])
total_invocations = sum(d['Sum'] for d in invocations_response['Datapoints'])
error_rate = (total_errors / total_invocations * 100) if total_invocations > 0 else 0
return {
'average_duration': avg_duration,
'error_rate': error_rate,
'invocation_count': int(total_invocations),
'total_errors': int(total_errors)
}
except Exception as e:
print(f'获取函数统计信息失败: {e}')
return {}
def measure_cold_start_time(self, function_name: str) -> float:
"""测量冷启动时间"""
try:
# 通过多次调用测量冷启动时间
cold_start_times = []
for i in range(3):
start_time = time.time()
# 调用函数
response = self.lambda_client.invoke(
FunctionName=function_name,
Payload=json.dumps({'test': 'cold_start'})
)
end_time = time.time()
cold_start_times.append(end_time - start_time)
# 等待一段时间确保函数冷却
time.sleep(60)
# 返回平均冷启动时间
return sum(cold_start_times) / len(cold_start_times) if cold_start_times else 0
except Exception as e:
print(f'测量冷启动时间失败: {e}')
return 0
def analyze_function_code(self, function_name: str) -> Dict[str, Any]:
"""分析函数代码"""
try:
# 获取函数代码
response = self.lambda_client.get_function(FunctionName=function_name)
code_location = response['Code']['Location']
# 下载代码包
import urllib.request
with urllib.request.urlopen(code_location) as response:
code_zip = response.read()
# 分析ZIP包
analysis = self.analyze_zip_package(code_zip)
return analysis
except Exception as e:
print(f'分析函数代码失败: {e}')
return {}
def analyze_zip_package(self, zip_data: bytes) -> Dict[str, Any]:
"""分析ZIP包"""
try:
with zipfile.ZipFile(io.BytesIO(zip_data)) as zip_file:
files = zip_file.namelist()
analysis = {
'file_count': len(files),
'total_size': len(zip_data),
'file_types': defaultdict(int),
'large_files': [],
'dependencies': []
}
for file in files:
# 统计文件类型
ext = os.path.splitext(file)[1].lower()
analysis['file_types'][ext] += 1
# 检查大文件
file_info = zip_file.getinfo(file)
if file_info.file_size > 1024 * 1024: # 1MB
analysis['large_files'].append({
'name': file,
'size': file_info.file_size
})
# 检查依赖文件
if file.endswith('requirements.txt') or file.endswith('package.json'):
analysis['dependencies'].append(file)
return analysis
except Exception as e:
print(f'分析ZIP包失败: {e}')
return {}
def calculate_monthly_cost(self, function_config: Dict, function_stats: Dict) -> float:
"""计算月度成本"""
try:
# AWS Lambda定价 (示例价格,实际价格可能变化)
# 免费额度:100万次请求,400,000 GB-秒计算时间
# 超出免费额度:$0.20 per 1M requests, $0.0000166667 per GB-second
memory_mb = function_config['MemorySize']
avg_duration_ms = function_stats.get('average_duration', 0) * 1000
invocations = function_stats.get('invocation_count', 0)
# 计算计算时间 (GB-秒)
compute_time_gb_sec = (memory_mb / 1024) * (avg_duration_ms / 1000) * invocations
# 计算请求成本
request_cost = max(0, invocations - 1000000) * 0.20 / 1000000
# 计算计算时间成本
compute_cost = max(0, compute_time_gb_sec - 400000) * 0.0000166667
total_cost = request_cost + compute_cost
return total_cost
except Exception as e:
print(f'计算成本失败: {e}')
return 0
def check_function_issues(self, metrics: FunctionMetrics, code_analysis: Dict) -> None:
"""检查函数问题"""
# 检查冷启动时间
if metrics.cold_start_time > 5.0:
self.issues.append(FunctionIssue(
severity='high',
type='performance',
function_name=metrics.name,
message=f'冷启动时间过长: {metrics.cold_start_time:.2f}秒',
suggestion='优化函数包大小,使用预热策略或选择更小的运行时',
affected_metrics=['cold_start_time', 'performance']
))
# 检查内存配置
if metrics.memory_size > 1024:
self.issues.append(Fu

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
51
Repository forks
13
7-day trend score
20

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/microwind/ai-skills/serverless-functions/badge)](https://verified-skill.com/skills/microwind/ai-skills/serverless-functions)

Something wrong with this skill or its page? Tell us.