declare local var.sample_percent INTEGER;
declare local var.pace INTEGER;
declare local var.start_hour INTEGER;
declare local var.end_hour INTEGER;
declare local var.current_hour INTEGER;

# Apply only to...
if (
  client.requests == 1 && # new connections
  fastly.ff.visits_this_service == 0 && # requests not forwarded from another Fastly data center
  req.restarts == 0 && # requests that haven't been restarted
  req.http.fastly-client-ip !~ throttling_exclusion_acl && # users not on the trusted list
  table.lookup(throttling_config, client.geo.country_code, "") ~ "^(\d+)\|(\d+)-(\d+)\|(\d+)$" # countries with valid throttling config
) {
  set var.sample_percent = std.atoi(re.group.1);
  set var.start_hour = std.atoi(re.group.2);
  set var.end_hour = std.atoi(re.group.3);
  set var.pace = std.atoi(re.group.4);
  set var.current_hour = std.atoi(strftime({"%H"}, now));

  # Apply the limit to only {var.sample_percent} of traffic
  if (var.sample_percent > randomint(0,99)) {
    if (var.start_hour > var.end_hour) {
      set var.end_hour += 24;
      if (var.current_hour < var.start_hour) {
        set var.current_hour += 24;
      }
    }

    # Apply only during the specified time window
    if (var.current_hour >= var.start_hour && var.current_hour < var.end_hour) {
      set client.socket.pace = std.atoi(var.pace);
      log "Pace limit in effect: ip=" + req.http.fastly-client-ip + " country=" + client.geo.country_code + " pace=" + client.socket.pace;
    }
  }
}