Randomness-related VCL features

Fastly provides several functions in VCL that control randomness-related activities.

Random strings

Use the function randomstr(length [, characters]). When characters aren't provided, the default will be the 64 characters of A-Za-z0-9_-.

sub vcl_deliver {
  set resp.http.Foo = "randomstuff=" randomstr(10);
  set resp.http.Bar = "morsecode=" randomstr(50, ".-"); # 50 dots and dashes

Random content cookies in pure VCL

sub vcl_deliver {
  add resp.http.Set-Cookie = "somerandomstuff=" randomstr(10) "; expires=" now + 180d "; path=/;";

This adds a cookie named "somerandomstuff" with 10 random characters as value, expiring 180 days from now.

Random decisions

Use the function randombool( _numerator_, _denominator_ ), which has a numerator/denominator chance of returning true.

sub vcl_recv {
  if (randombool(1, 4)) {
    set req.http.X-AB = "A";
  } else {
    set req.http.X-AB = "B";

This will add a X-AB header to the request, with a 25% (1 out of 4) chance of having the value "A", and 75% chance of having the value "B".

The randombool() function accepts INT function return values, so you could do something this:

if (randombool(std.atoi(req.http.Some-Header), 100))  {
  # do something

Another function, randombool_seeded(), takes an additional seed argument. Results for a given seed will always be the same. For instance, in this example the value of the response header will always be no:

if (randombool_seeded(50, 100, 12345)) {
  set resp.http.Seeded-Value = "yes";
} else {
  set resp.http.Seeded-Value = "no";

This could be useful for stickiness. For example, if you based the seed off of something that identified a user, you could perform A/B testing without setting a special cookie.

Back to Top