코딩

AWS CDK 构建 SageMaker 端点自动扩缩

Updating a SageMaker AI endpoint that has Application Auto Scaling registered makes AWS CloudFormation and AWS CDK deployments fail. This post shows how to build a reusable AWS CDK

본문은 SEO 깊이를 위해 주로 중국어입니다. 위는 현지화 요점입니다. 언어 전환·딥링크로 글로벌 탐색하세요.

# AWS CDK 构建 SageMaker 端点自动扩缩

AWS CDK 构建 SageMaker 端点自动扩缩的核心价值在于解决生产环境流量波动时,注册 Application Auto Scaling 的端点在 AWS CloudFormation 或 CDK 部署中遇到的失败问题。通过 CDK 的声明式代码,您可以一次性定义基础端点配置、自动扩缩策略,并确保资源创建成功。这适用于所有希望在 AWS 上稳定托管大模型推理服务的开发者,无论是单实例测试还是高并发生产环境。决策时优先考虑 CDK 优势:代码可版本化、可重用模块化部署,且能直接集成现有 CDK 栈,避免手动 CloudFormation 模板的维护负担。

SageMaker 端点与自动扩缩基础

Amazon SageMaker 端点是托管机器学习模型的托管服务,支持实时推理。自动扩缩功能通过 Application Auto Scaling 动态调整实例数量,以应对请求激增或低谷,避免队列延迟或资源浪费。

典型问题:一旦端点已关联 Application Auto Scaling,标准 CloudFormation 部署或 CDK 合成会因资源冲突失败。AWS CDK 提供专用资源类型(如 ScalableInstanceCount),允许在 TypeScript 或 Python 中优雅定义扩缩参数。

场景与适用条件

  • 高流量推理场景:API 端点用于在线 Grok API 中转或本地部署模型服务,峰值流量可能导致实例不足。
  • 低成本优化:按需调整实例,避免长时间闲置。
  • 决策依据:如果您的项目已使用 CDK 管理基础设施,此方法能直接复用现有代码库,无需额外迁移。

扩缩策略举例

策略类型触发条件调整方向适用场景
TargetTracking自定义请求百分比阈值增减实例稳定流量波动(推荐首选)
StepScaling特定警报(如 CPU 利用率)线性或指数突发高峰(如模型天梯测试)
SimpleScaling固定间隔 + 阈值固定步长简单成本控制场景

AWS CDK 构建 SageMaker 端点自动扩缩实践

GrokCode 实验室推荐使用 AWS CDK 构建 SageMaker 端点自动扩缩,因为它将基础设施作为代码,实现自动化部署与监控集成。

CDK 安装与栈初始化

``bash npm install -g aws-cdk cdk init app -l typescript ``

在 lib/app-stack.ts 中,引入 SageMaker 模块:

```typescript import * as cdk from 'aws-cdk-lib'; import * as sagemaker from 'aws-cdk-lib/aws-sagemaker'; import * as iam from 'aws-cdk-lib/aws-iam';

export class AppStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props);

// 基础 SageMaker 端点 const endpoint = new sagemaker.CfnEndpoint(this, 'MySageMakerEndpoint', { endpointName: 'my-endpoint', endpointConfigName: 'my-endpoint-config', deploymentConfig: { // 初始实例 productionVariants: [{ variantName: 'AllTraffic', modelName: 'my-model', initialInstanceCount: 1, instanceType: 'ml.m5.large', }], }, });

// 自动扩缩 - TargetTracking 策略 new sagemaker.ScalableInstanceCount(this, 'AutoScale', { endpointName: endpoint.endpointName, dimension: 'DesiredInstanceCount', serviceNamespace: 'sagemaker', resourceId: endpoint/${endpoint.endpointName}/variant/AllTraffic, role: new iam.Role(this, 'ScalingRole', { assumedBy: new iam.ServicePrincipal('application-autoscaling.amazonaws.com'), }), minCapacity: 1, maxCapacity: 10, // 可选:精确匹配 TargetTracking 的 ScalingPolicy });

// 输出 new cdk.CfnOutput(this, 'EndpointUrl', { value: endpoint.attrEndpointUrl, }); } } ```

合成与部署命令: ``bash cdk synth cdk deploy ``

此配置确保端点创建后立即绑定扩缩策略,解决注册冲突问题。

策略配置优化

根据负载特点调整参数:

  • TargetTracking:设置目标 CPU 利用率 50%,自动调节实例。
  • StepScaling:配合 CloudWatch 警报,定义冷却时间避免震荡。
  • 模块化复用:将策略抽取为单独类,便于跨项目复用。

常见问题与解决方案

部署失败多因扩缩配置与基础端点不匹配。检查步骤:

  1. 确保 productionVariants 中包含 DesiredInstanceCount。
  2. 角色权限已授予 application-autoscaling 服务。
  3. 端点名称在 CDK 栈中唯一。

延伸阅读

  • [GrokCode API 中转平台]
  • [GrokCode 模型天梯实验室]
  • [GrokCode 开源本地部署工具]
  • [GrokCode 编程实践指南]

风险与边界

此方法依赖 AWS CDK 与 SageMaker 官方 API,无需解锁或注入任何非官方工具。仅作为技术参考,不构成法律意见或业务建议。请根据您的实际 AWS 账户权限与合规要求操作。如遇部署失败,请参考 AWS 官方文档排查资源冲突。使用此指南需承担相应风险,包括资源成本与服务可用性问题。

English summary

Building a SageMaker endpoint with automatic scaling using AWS CDK solves deployment failures that occur when Application Auto Scaling is already registered. This guide provides a complete, reusable TypeScript example that defines the endpoint configuration, production variants, and scaling policies in one stack. Developers on AWS can directly deploy production-grade inference endpoints for high-traffic scenarios such as model serving or API transit. Key steps include initializing a CDK app, creating a CfnEndpoint, and adding ScalableInstanceCount for dynamic instance adjustment. The approach ensures version-controlled infrastructure, easy integration with existing stacks, and support for strategies like target tracking. It is suitable for teams managing large language models or local deployment workloads. Always test in a non-production environment and monitor CloudWatch metrics post-deployment. This method reduces manual errors and supports scalable, cost-efficient AI workloads on AWS.

适用于 GrokCode 倍率榜。信息仅供参考,不构成购买、投资或法律意见。