How to limit a hostname to not have more than 1000 visits

What is the name of the domain?

example.com

What is the issue you’re encountering

I want to block any requests to a hostname if it receives more than 1,000 visits, regardless of whether those visits come from 1,000 unique IPs or a single IP address.

You’d have to use something like a Worker and KV to count requests, then stop blocking as soon as the KV hits 1000.

Here’s code ChatGPT recommended:

export default {
  async fetch(request, env) {
    // Bind the KV namespace
    const kvNamespace = env.REQUESTS_COUNTER;
    const limit = 1000; // Set the request limit

    // Use a constant key to track the count
    const counterKey = "requests_count";

    // Retrieve the current counter value from KV
    let counter = await kvNamespace.get(counterKey);

    // Parse counter value (default to 0 if null)
    counter = counter ? parseInt(counter, 10) : 0;

    if (counter >= limit) {
      // Block the request if the limit is reached
      return new Response("Request limit reached. Please try again later.", {
        status: 429,
        headers: {
          "Content-Type": "text/plain",
        },
      });
    }

    // Increment the counter and update the KV store
    counter++;
    await kvNamespace.put(counterKey, counter.toString());

    // Proceed with the normal request flow
    return new Response("Request allowed. Counter: " + counter, {
      status: 200,
      headers: {
        "Content-Type": "text/plain",
      },
    });
  },
};

Then bind your Worker to a KV, and assign the Worker to a route, like example.com/*

Make sure the Worker’s workers.dev hostname and any preview URLs are Disabled under Settings for that works, so requests for the worker itself don’t increment the counter.

If using Workers is new to you, the best place to get coding assistance is on the Discord:

@leo18 I’m curious: What’s the point of this? What happens when a hostname receives more than 1,000 visits? And are we talking 1,000 visits ever? Monthly? Daily?

I’m just curious :smiley:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.