Injecting Chaos to AWS Lambda functions using Lambda Layers

Adrian Hornsby
Jan 4, 2019 · 10 min read

“As far as the laws of mathematics refer to reality, they are not certain, and as far as they are certain, they do not refer to reality.” -Albert Einstein

UPDATE — October 2019

Why latency injection?

“Failures are a given, and everything will eventually fail over time.”

Before we get started

{ 
"delay": 300,
"isEnabled": true
}
from ssm_cache import SSMParameter
param = SSMParameter('chaoslambda.config')
def get_config():
param = SSMParameter('chaoslambda.config')
try:
value = json.loads(param.value)
delay = value["delay"]
isEnabled = value["isEnabled"]
if isEnabled and delay >= 0:
return delay
elif isEnabled and delay <= 0:
return -1
else:
return 0
except InvalidParameterError as e:
print("{} is not SSM".format(e))
return 0
except KeyError as e:
print("{} is not a valid Key in SSM configuration".format(e))
return 0
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:DescribeParameters"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:eu-north-1:<ACCOUNT_ID>:parameter/chaoslambda.config"
}
]
}
import os
region = os.environ["AWS_REGION"]
tablename = os.environ["tablename"]
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table(tablename)

Latency injections using Python.

1 — Using a Python decorator

from __future__ import division, unicode_literals
import time
import random
def delayit(func):
def latency(*args, **kw):
delay = get_config()
start = time.time()
# if delay exist and bigger than 0, delaying with that value
if delay > 0:
time.sleep(delay / 1000.0)
# if delay is negative make random delays
elif delay < 0:
# add latency approx 50% of the time
if random.random() > 0.5:
# random sleep time between 1 and 10 seconds
time.sleep(random.randint(1, 10))
result = func(*args, **kw)
end = time.time()
print('Added {1:.2f}ms to {0:s}'.format(
func.__name__,
(end - start) * 1000
))
return result
return latency
from chaos_lib import delayit@delayit
def dummy():
pass
def lambda_handler(event, context):
dummy()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}

2 — Subclassing the requests library

class SessionWithDelay(requests.Session):
def __init__(self, delay=None, *args, **kwargs):
super(SessionWithDelay, self).__init__(*args, **kwargs)
self.delay = delay
def request(self, method, url, **kwargs):
print('Added {1.2f}ms of delay to {0:s}'.format(
method, self.delay))
time.sleep(self.delay / 1000.0)
return super(SessionWithDelay, self).request(method, url, **kwargs)
from chaos_lib import SessionWithDelaydef dummy():
session = SessionWithDelay(delay=300)
session.get('https://stackoverflow.com/')
pass
def lambda_handler(event, context):
dummy()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}

Building the ZIP package for the Lambda Layer

$ git clone git@github.com:adhorn/LatencyInjectionLayer.git
$ git checkout tags/v0.1-alpha
$ docker run -v $PWD:/var/task -it lambci/lambda:build-python3.6 /bin/bash -c "pip install -r python/requirements.txt -t ./python/.vendor"
$ zip -r chaos_lib.zip ./python

Creating a Lambda Layer from the Chaos Library

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"ssm:DescribeParameters",
"logs:CreateLogGroup",
"logs:PutLogEvents"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:eu-north-1:<YOURACCOUNTID>:parameter/chaoslambda.config"
}
]
}
from chaos_lib import delayit
from chaos_lib import SessionWithDelay

def dummy2():
session = SessionWithDelay(delay=300)
session.get('https://stackoverflow.com/')
pass

@delayit

def dummy():
pass

def lambda_handler(event, context):
dummy()
dummy2()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}
from chaos_lib import delayit
from chaos_lib import SessionWithDelay
Yes, I am on version 5 already :-)

Wrapping up.

The Cloud Architect

Resilient, scalable, and highly available cloud architectures.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store