# AWS Lambda — Random numbers go Serverless

Dec 26, 2019 · 3 min read

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-getting-started-with-rest-apis.html

Ernie was about Premium bonds issued by the U.K. government back in the 50’s. The government pays interest into the bond fund (1.40% per annum since 2017)[1] from which a monthly lottery distributes tax-free prizes to bondholders whose numbers are selected randomly. The machine that generates the numbers is called ERNIE, for Electronic Random Number Indicator Equipment.[2] Prizes range from £25 to £1,000,000 and (since 2017) the odds of a £1 bond winning a prize in a given month are 24,500 to 1.[3]

That’s the story, lets get started with Amazon AWS Lambda to create a random number generator [LCG (linear congruential generator] and expose it through an API Gateway.
Source: https://rosettacode.org/wiki/Linear_congruential_generator

Steps:

1. Create the Lambda function: ernie
that performs the random number generation.
2. Create the API Gateway

Lambda function: ernie

Go to Services> Create Function
Under Function code, choose Runtime Node.js 12.x and have the following code pasted:

exports.handler = async (event) => {

var lcg = (function() {
// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
// m is basically chosen to be large (as it is the max period)
// and for its relationships to a and c
var m = 4294967296,
// a — 1 should be divisible by m’s prime factors
a = 1664525,
// c and m should be co-prime
c = 1013904223,
seed, z;
return {
setSeed : function(val) {
z = seed = val || Math.round(Math.random() * m);
},
getSeed : function() {
return seed;
},
rand : function() {
// define the recurrence relationship
z = (a * z + c) % m;
// return a float in [0, 1)
// if z = m then z / m = 0 therefore (z % m) / m < 1 always
return z & 0x3fffffff;
}
};
}());

lcg.setSeed()
var val = lcg.rand()

// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify(val),
};
return response;
};

Save it

2. Create the Amazon API Gateway

Refer here: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-getting-started-with-rest-apis.html for step by step instructions

Snapshot below:

And that’s it, we now have a Serverless RNG (Random number generator) in minutes.

curl -X GET ‘https://abr79lbkd7.execute-api.us-east-1.amazonaws.com/prod'
{“statusCode”:200,”body”:”659754301"}

curl -X GET ‘https://abr79lbkd7.execute-api.us-east-1.amazonaws.com/prod'
{“statusCode”:200,”body”:”147775454"}

Every time you call it, gives you a random number. This is an Amazon API Gateway with Lambda integration.

Written by

## More From Medium

Nov 23, 2019 · 5 min read

#### 75

Oct 28, 2019 · 7 min read