以 ad_id 為 Partition Key , click_id 為 Sort Key ,可以藉由 ad_id 分析每個廣告的點擊率。
AdClickTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub 'ad-clicks-${Environment}'
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: ad_id
AttributeType: S
- AttributeName: click_id
AttributeType: S
KeySchema:
- AttributeName: ad_id
KeyType: HASH
- AttributeName: click_id
KeyType: RANGE
StreamSpecification:
StreamViewType: NEW_AND_OLD_IMAGES
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Application
Value: AdClickAggregator
其他欄位還有 impression_id ,可以追蹤這個廣告是在哪裡曝光,藉此分析出在哪邊投放廣告最有效。
因為 API Gateway 需要整合 SQS ,所以 API Gateway 的 role 要有 SQS SendMessage 的權限,如果還需要寫 log 到 CloudWatch ,還需要 CloudWatch 的權限。
ApiGatewaySQSRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: SendMessageToSQS
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- sqs:SendMessage
Resource: !GetAtt AdClickQueue.Arn
另外,因為 Lambda 也需要 role ,所以需要額外生成一個 role 給 Lambda 使用,盡量不要共用 role ,這樣才能符合最小權限原則。這個 role 要有存取 dynamodb 和 sqs 的權限,因為 Lambda 需要從 SQS 讀取 message ,然後把資料寫到 dynamodb 。
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub 'ad-click-lambda-role-${Environment}'
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: DynamoDBAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:GetItem
- dynamodb:Query
Resource: !GetAtt AdClickTable.Arn
- PolicyName: SQSAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- sqs:ReceiveMessage
- sqs:DeleteMessage
- sqs:GetQueueAttributes
Resource: !GetAtt AdClickQueue.Arn
這個架構的簡介就到這裡,要看完整的 Cloudformation template,可以到 Medium 。
Medium: 使用 Serverless 架構設計廣告點擊系統(Ad Click Aggregator)