How to create a Custom code FlexBalancer

Creating your very first simple Custom Balancer

First of all, log in and proceed to the FlexBalancers page:

create_page_1

Select a name for your Balancer, choose `Custom code` button and press `Next Step`:

create_page_2

Then, fill in your `fallback` address. You may also change default `TTL`, or keep it equal to 10. After that, press `Create New FlexBalancer` button:

create_page_3

Now, you have text editor open, so you can write or post there your custom code.

Supported language: `TypeScript`. 
Editor: Monaco Editor, see Monaco Editor Accessibility Guide for detailed info. Notice, that you also are able to edit FlexBalancer description, Fallback and TTL.

Let's create our first Custom FlexBalancer with the simplest logic: we will check uptime of `jsDelivr CDN` and if it is bigger that 98,5 - return answer 'google.com' with TTL 25, if not - return 'perfops.net' with default TTL (that you have set before).

/* 
* If jsDelivr uptime is bigger than 98,5 - return 'google.com' with TTL 25
* else return 'perfops.net' with default TTL
*/
function onRequest(req: IRequest, res: IResponse) {
if(fetchCdnRumUptime('jsdelivr-cdn') > 98.5) { // if jsDelivr uptime is high
res.setAddr('google.com'); // we set answer address to 'google.com'
res.setTTL(25); // with TTL = 25

return; // return answer
}
// if jsDelivr uptime is lower than expected
res.setAddr('perfops.net'); // we set answer address to 'perfops.net'
return; // return answer
}

The text editor checks your code syntax for errors, shows error details on mouse hover and won't allow you to publish code with errors:

create_page_4

It also 'knows' all definitions of PerfOps Custom Answers API (functions, type values for particular user) and provides helpful hints (use `Ctrl+Space`) and auto-completion (use `Tab`):

create_page_5

create_page_6

Now all changes are done and no errors remain, you simply press `Test and Publish` button and confirm the deployment:

create_page_7

The next page has important information, do not forget to copy/save `CNAME` record for further placement into domain settings for your domain, then press `Done`:

create_page_8

Now you can see your newly created FlexBalancer at `FlexBalancers` page:

create_page_9

Let's check if your Custom Answer works. After some time, when you already have made all nessessary `CNAME` changes - check CDN RUM Uptime at CDNPerf.


You can see that RUM Uptime is higher than `98,5`.

cdn_statistics

So, according to rules that you have defined at Custom Answer, it should return `google.com` as response address.

dig_results

And it does! That means your FlexBalancer works perfectly!

You may want to take a look at our Tutorial and at more complicated script samples stored at our repository.