Running R Script on AWS Lambda Custom Runtime

Sample: Plotting Cars Dataset

This image is a plot of cars dataset, drawn by R on AWS Lambda. It uses Custom Runtimes announced at re:invent 2018. This entry describes how to create and invoke the function.

The main script plot.R has only 3 lines.

library(txtplot)
require(stats)
txtplot(cars[,1], cars[,2], xlab = "speed", ylab = "distance")

Lambda and the custom runtime will look after the remaining process.

How to Create and Invoke

Clone the GitHub repository.

$ git clone https://github.com/vt-iwamoto/aws-lambda-r-playground

Build a Docker image tagged aws-lambda-r-playground, including R and txtplot.

$ cd aws-lambda-r-playground
$ docker build -t aws-lambda-r-playground .

Create function.zip including R, libraries, bootstrap and plot.R.

$ docker run --rm -v $(pwd):/opt/work \
aws-lambda-r-playground /opt/work/zip_function.sh

Create an AWS Lambda function named r-test. The timeout should be better to extend from 3.

$ aws lambda create-function \
--function-name r-test \
--zip-file fileb://function.zip \
--handler plot \
--runtime provided \
--role {ARN of this function's execution role} \
--timeout 10

Invoke the function.

$ aws lambda invoke --function-name r-test output.txt
{
"ExecutedVersion": "$LATEST",
"StatusCode": 200
}
$ cat output.txt && echo
+----+-----------+------------+-----------+-----------+--+
120 + * +
| |
d 100 + * +
i | * * |
s 80 + * * +
t | * * * * |
a 60 + * * * * * +
n | * * * * * |
c 40 + * * * * * * * +
e | * * * * * * * |
20 + * * * * * +
| * * * |
0 +----+-----------+------------+-----------+-----------+--+
5 10 15 20 25
speed

Notes

  • The size of function.zip can be reduced by editing zip_function.sh.
  • bootstrap passes the event data to R. It will be interesting to try it.
  • It will be also interesting to create a R layer to support multiple functions.