-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathkinesis_scaling_cf.yaml
515 lines (487 loc) · 19.5 KB
/
kinesis_scaling_cf.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
AWSTemplateFormatVersion: "2010-09-09"
#
# Note:
# For the Lambda code use the provided kinesis_scaling.zip and place it in the
# root of your S3CodeBucket. You can also build your own with the following
# steps (using go 1.15.x) or the build script in the repo:
# GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main scale.go
# zip kinesis_scaling.zip main
#
Parameters:
S3CodeBucket:
Type: String
Description: S3 Bucket containing the compiled 'kinesis_scaling.zip' golang Lambda
Default: kinesis-scaling-code-bucket
S3CodeKey:
Type: String
Description: S3 filename containing the 'kinesis_scaling.zip' golang Lambda
Default: kinesis_scaling.zip
KinesisScaleUpThreshold:
Type: Number
Description: At what total usage should streams scale up? Handles both bytes/sec and records/sec (1.0 = 100%)
Default: 0.75
KinesisScaleDownThreshold:
Type: Number
Description: At what total usage should streams scale down? Handles both bytes/sec and records/sec (1.0 = 100%)
Default: 0.25
KinesisScaleDownMinIterAgeMins:
Type: Number
Description: Do not scale down the stream if it is this many minutes behind. Example 30 minutes (-1 to disable)
Default: -1
ScalingDryRun:
Type: String
Description: If this is set to true, the lambda function will not scale the stream. This flag can be used to monitor how the stack performs without actually scaling the stream.
Default: false
AllowedValues:
- true
- false
Resources:
###############################################################################
#
# Auto Scaling Lambda
#
###############################################################################
AutoScalingLambda:
DependsOn: AutoScalingLambdaRole
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub '${AWS::StackName}-kinesis-scaling'
Runtime: go1.x
Role: !GetAtt AutoScalingLambdaRole.Arn
Handler: main
ReservedConcurrentExecutions: 1 # Dont allow multiple copies to run simultaneously
MemorySize: 512
Timeout: 900
Code:
S3Bucket: !Ref S3CodeBucket
S3Key: !Ref S3CodeKey
Environment:
Variables:
THROTTLE_RETRY_MIN_SLEEP: 1
THROTTLE_RETRY_MAX_SLEEP: 3
THROTTLE_RETRY_COUNT: 30
SCALE_PERIOD_MINS: 5 # kinesis_period_mins: cloudwatch datapoint period in minutes (default is 5, changing this is not recommended)
SCALE_UP_THRESHOLD: !Ref KinesisScaleUpThreshold
SCALE_UP_EVALUATION_PERIOD: 5 # 25 Minutes / kinesis_period_mins. Evaluate scale up for 25 minutes.
SCALE_UP_DATAPOINTS_REQUIRED: 5 # 25 Minutes / kinesis_period_mins. 5 out of 5 datapoints required. Takes 25 minutes above threshold to scale up.
SCALE_DOWN_THRESHOLD: !Ref KinesisScaleDownThreshold
SCALE_DOWN_EVALUATION_PERIOD: 60 # 300 Minutes / kinesis_period_mins. Evaluate scale down for 300 minutes.
SCALE_DOWN_DATAPOINTS_REQUIRED: 57 # 285 Minutes / kinesis_period_mins. 57 out of 60 datapoints required. Takes 285 minutes below threshold to scale down.
SCALE_DOWN_MIN_ITER_AGE_MINS: !Ref KinesisScaleDownMinIterAgeMins
PROCESSING_LAMBDA_ARN: "" # Empty = No Op, or if scaling a single stream, set this to the lambda consumer arn to automatically reserve concurrency as the stream scales
PROCESSING_LAMBDAS_PER_SHARD: 5 # Lambdas per shard used by the above processing lambda
DRY_RUN: !Ref ScalingDryRun # Dry run flag (true or false) indicating whether streams will be scaling or not.
AutoScalingLambdaAsyncConfig:
Type: AWS::Lambda::EventInvokeConfig
DependsOn: AutoScalingLambda
Properties:
FunctionName: !Sub '${AWS::StackName}-kinesis-scaling'
MaximumRetryAttempts: 0 # We do not want any retries of the scaling function if it errors out, alarms will re-trigger it
Qualifier: $LATEST
#
# Auto Scaling Lambda IAM Role
#
AutoScalingLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: AllowCreateCloudWatchAlarms
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'cloudwatch:DescribeAlarms'
- 'cloudwatch:GetMetricData'
- 'cloudwatch:ListMetrics'
- 'cloudwatch:PutMetricAlarm'
- 'cloudwatch:PutMetricData'
- 'cloudwatch:ListTagsForResource'
- 'cloudwatch:SetAlarmState'
- 'cloudwatch:TagResource'
Resource:
- !Sub 'arn:aws:cloudwatch:${AWS::Region}:${AWS::AccountId}:alarm:${AWS::StackName}-AutoScalingStream*'
- PolicyName: AllowLoggingToCloudWatch
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource:
- !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${AWS::StackName}-kinesis-scaling:*'
- PolicyName: AllowReadFromKinesis
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'kinesis:DescribeStreamSummary'
- 'kinesis:AddTagsToStream'
- 'kinesis:ListTagsForStream'
- 'kinesis:UpdateShardCount'
Resource:
- !Sub 'arn:aws:kinesis:${AWS::Region}:${AWS::AccountId}:stream/${AWS::StackName}-AutoScalingStream*'
- PolicyName: AllowPublishToSNS
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'sns:Publish'
Resource:
- !Sub 'arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${AWS::StackName}-kinesis-scaling-topic'
- PolicyName: AllowChangeFunctionConcurrencyForLambda
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'lambda:PutFunctionConcurrency'
- 'lambda:DeleteFunctionConcurrency'
Resource:
- !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-your-kinesis-consumer-function-name-here'
###############################################################################
#
# Auto Scaling SNS Topic
#
###############################################################################
AutoScalingSNSTopic:
Type: AWS::SNS::Topic
DependsOn: AutoScalingLambda
Properties:
Subscription:
- Endpoint: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-kinesis-scaling'
Protocol: "lambda"
TopicName: !Sub '${AWS::StackName}-kinesis-scaling-topic'
AutoScalingSNSTopicLambdaPerm:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !Sub '${AWS::StackName}-kinesis-scaling'
Principal: "sns.amazonaws.com"
SourceArn: !Ref AutoScalingSNSTopic
###############################################################################
#
# Kinesis Data Stream 01
#
###############################################################################
AutoScalingStream01:
Type: AWS::Kinesis::Stream
Properties:
ShardCount: 1
#
# Kinesis Data Stream 01 - Scale Up Alarm
#
AutoScalingStream01ScaleUpAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn: [ AutoScalingStream01, AutoScalingSNSTopic ]
Properties:
AlarmName: !Join ['', [!Ref AutoScalingStream01, '-scale-up']]
AlarmDescription: 'Stream throughput has gone above the scale up threshold'
ComparisonOperator: GreaterThanOrEqualToThreshold
Threshold: !Ref KinesisScaleUpThreshold
EvaluationPeriods: 5 # 25 Minutes / kinesis_period_mins. Evaluate scale up for 25 minutes.
DatapointsToAlarm: 5 # 25 Minutes / kinesis_period_mins. 5 out of 5 datapoints required. Takes 25 minutes above threshold to scale up.
AlarmActions: [ !Ref AutoScalingSNSTopic ]
Metrics:
- Id: s1
ReturnData: False
Label: ShardCount
Expression: 1
- Id: m1
ReturnData: False
Label: IncomingBytes
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingBytes
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream01
- Id: m2
ReturnData: False
Label: IncomingRecords
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingRecords
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream01
- Id: e1
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingBytes
Expression: FILL(m1,0)
- Id: e2
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingRecords
Expression: FILL(m2,0)
- Id: e3
ReturnData: False
Label: IncomingBytesUsageFactor
Expression: e1/(1024*1024*60*5*s1) # e1/(1024*1024*60*${kinesis_period_mins}*s1)
- Id: e4
ReturnData: False
Label: IncomingRecordsUsageFactor
Expression: e2/(1000*60*5*s1) # e2/(1000*60*${kinesis_period_mins}*s1)
- Id: e5
ReturnData: True
Label: MaxIncomingUsageFactor
Expression: MAX([e3,e4]) # Take the highest usage factor between bytes/sec and records/sec
#
# Kinesis Data Stream 02 - Scale Down Alarm
#
AutoScalingStream01ScaleDownAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn: [ AutoScalingStream01, AutoScalingSNSTopic ]
Properties:
AlarmName: !Join ['', [!Ref AutoScalingStream01, '-scale-down']]
AlarmDescription: 'Stream throughput has gone below the scale down threshold'
ComparisonOperator: LessThanThreshold
Threshold: -1 # Set to -1 for 1 shard stream, as we can't scale down from here. Gets updated by the auto scaling lambda later
EvaluationPeriods: 60 # 300 Minutes / kinesis_period_mins. Evaluate scale down for 300 minutes.
DatapointsToAlarm: 57 # 285 Minutes / kinesis_period_mins. 57 out of 60 datapoints required. Takes 285 minutes below threshold to scale down.
AlarmActions: [ !Ref AutoScalingSNSTopic ]
Metrics:
- Id: s1
ReturnData: False
Label: ShardCount
Expression: 1
- Id: s2
ReturnData: False
Label: IteratorAgeMinutesToBlockScaledowns
Expression: !Ref KinesisScaleDownMinIterAgeMins
- Id: m1
ReturnData: False
Label: IncomingBytes
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingBytes
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream01
- Id: m2
ReturnData: False
Label: IncomingRecords
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingRecords
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream01
- Id: m3
ReturnData: False
Label: GetRecords.IteratorAgeMilliseconds
MetricStat:
Stat: Maximum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: GetRecords.IteratorAgeMilliseconds
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream01
- Id: e1
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingBytes
Expression: FILL(m1,0)
- Id: e2
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingRecords
Expression: FILL(m2,0)
- Id: e3
ReturnData: False
Label: IncomingBytesUsageFactor
Expression: e1/(1024*1024*60*5*s1) # e1/(1024*1024*60*${kinesis_period_mins}*s1)
- Id: e4
ReturnData: False
Label: IncomingRecordsUsageFactor
Expression: e2/(1000*60*5*s1) # e2/(1000*60*${kinesis_period_mins}*s1)
- Id: e5
ReturnData: False
Label: IteratorAgeAdjustedFactor
Expression: !Sub (FILL(m3,0)/1000/60)*(${KinesisScaleDownThreshold}/s2) # We want to block scaledowns when IterAge is > 30 mins, multiply IterAge so 30 mins = <alarmThreshold>
- Id: e6
ReturnData: True
Label: MaxIncomingUsageFactor
Expression: MAX([e3,e4,e5]) # Take the highest usage factor between bytes/sec, records/sec, and adjusted iterator age
###############################################################################
#
# Kinesis Data Stream 02
#
###############################################################################
AutoScalingStream02:
Type: AWS::Kinesis::Stream
Properties:
ShardCount: 1
#
# Kinesis Data Stream 02 - Scale Up Alarm
#
AutoScalingStream02ScaleUpAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn: [ AutoScalingStream02, AutoScalingSNSTopic ]
Properties:
AlarmName: !Join ['', [!Ref AutoScalingStream02, '-scale-up']]
AlarmDescription: 'Stream throughput has gone above the scale up threshold'
ComparisonOperator: GreaterThanOrEqualToThreshold
Threshold: !Ref KinesisScaleUpThreshold
EvaluationPeriods: 5 # 25 Minutes / kinesis_period_mins. Evaluate scale up for 25 minutes.
DatapointsToAlarm: 5 # 25 Minutes / kinesis_period_mins. 5 out of 5 datapoints required. Takes 25 minutes above threshold to scale up.
AlarmActions: [ !Ref AutoScalingSNSTopic ]
Metrics:
- Id: s1
ReturnData: False
Label: ShardCount
Expression: 1
- Id: m1
ReturnData: False
Label: IncomingBytes
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingBytes
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream02
- Id: m2
ReturnData: False
Label: IncomingRecords
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingRecords
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream02
- Id: e1
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingBytes
Expression: FILL(m1,0)
- Id: e2
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingRecords
Expression: FILL(m2,0)
- Id: e3
ReturnData: False
Label: IncomingBytesUsageFactor
Expression: e1/(1024*1024*60*5*s1) # e1/(1024*1024*60*${kinesis_period_mins}*s1)
- Id: e4
ReturnData: False
Label: IncomingRecordsUsageFactor
Expression: e2/(1000*60*5*s1) # e2/(1000*60*${kinesis_period_mins}*s1)
- Id: e5
ReturnData: True
Label: MaxIncomingUsageFactor
Expression: MAX([e3,e4]) # Take the highest usage factor between bytes/sec and records/sec
#
# Kinesis Data Stream 02 - Scale Down Alarm
#
AutoScalingStream02ScaleDownAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn: [ AutoScalingStream02, AutoScalingSNSTopic ]
Properties:
AlarmName: !Join ['', [!Ref AutoScalingStream02, '-scale-down']]
AlarmDescription: 'Stream throughput has gone below the scale down threshold'
ComparisonOperator: LessThanThreshold
Threshold: -1 # Set to -1 for 1 shard stream, as we can't scale down from here. Gets updated by the auto scaling lambda later
EvaluationPeriods: 60 # 300 Minutes / kinesis_period_mins. Evaluate scale down for 300 minutes.
DatapointsToAlarm: 57 # 285 Minutes / kinesis_period_mins. 57 out of 60 datapoints required. Takes 285 minutes below threshold to scale down.
AlarmActions: [ !Ref AutoScalingSNSTopic ]
Metrics:
- Id: s1
ReturnData: False
Label: ShardCount
Expression: 1
- Id: s2
ReturnData: False
Label: IteratorAgeMinutesToBlockScaledowns
Expression: !Ref KinesisScaleDownMinIterAgeMins
- Id: m1
ReturnData: False
Label: IncomingBytes
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingBytes
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream02
- Id: m2
ReturnData: False
Label: IncomingRecords
MetricStat:
Stat: Sum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: IncomingRecords
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream02
- Id: m3
ReturnData: False
Label: GetRecords.IteratorAgeMilliseconds
MetricStat:
Stat: Maximum
Period: 300 # Must match kinesis_period_mins: 5 minutes. Convert to seconds. 300 seconds.
Metric:
MetricName: GetRecords.IteratorAgeMilliseconds
Namespace: AWS/Kinesis
Dimensions:
- Name: StreamName
Value: !Ref AutoScalingStream02
- Id: e1
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingBytes
Expression: FILL(m1,0)
- Id: e2
ReturnData: False
Label: FillMissingDataPointsWithZeroForIncomingRecords
Expression: FILL(m2,0)
- Id: e3
ReturnData: False
Label: IncomingBytesUsageFactor
Expression: e1/(1024*1024*60*5*s1) # e1/(1024*1024*60*${kinesis_period_mins}*s1)
- Id: e4
ReturnData: False
Label: IncomingRecordsUsageFactor
Expression: e2/(1000*60*5*s1) # e2/(1000*60*${kinesis_period_mins}*s1)
- Id: e5
ReturnData: False
Label: IteratorAgeAdjustedFactor
Expression: !Sub (FILL(m3,0)/1000/60)*(${KinesisScaleDownThreshold}/s2) # We want to block scaledowns when IterAge is > 30 mins, multiply IterAge so 30 mins = <alarmThreshold>
- Id: e6
ReturnData: True
Label: MaxIncomingUsageFactor
Expression: MAX([e3,e4,e5]) # Take the highest usage factor between bytes/sec, records/sec, and adjusted iterator age