Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Creating a Cloudflare Worker to implement rate limiting using Cloudflare's KV (Key-Value) storage involves a few steps. You'll want to check the value of a specific request header and use that to track and limit the number of requests from a client. Below is an example of how you can achieve this. This example uses the `X-Client-IP` header as the identifier, but you can modify it to use any header you prefer, such as `CF-Connecting-IP` for the client's IP address or a custom header for user identification.
- First, make sure you have a KV namespace bound to your worker. In the Cloudflare Workers dashboard, go to your worker, then "Settings" -> "Variables", and add a binding for your KV namespace. Let's call it `RATE_LIMIT`.
- The worker script might look something like this:
- ```javascript
- addEventListener('fetch', event => {
- event.respondWith(handleRequest(event.request))
- })
- async function handleRequest(request) {
- const identifier = request.headers.get('X-Client-IP') // Or any header you prefer
- if (!identifier) {
- return new Response('Identifier header missing', { status: 400 })
- }
- const key = `ratelimit:${identifier}`
- const currentCount = await RATE_LIMIT.get(key)
- const currentTime = Math.floor(Date.now() / 1000)
- if (currentCount) {
- const [lastTime, count] = currentCount.split(':').map(Number)
- if (currentTime - lastTime < 60 && count > 10) { // 60 seconds window, 10 requests limit
- return new Response('Rate limit exceeded', { status: 429 })
- }
- if (currentTime - lastTime < 60) {
- await RATE_LIMIT.put(key, `${currentTime}:${count + 1}`)
- } else {
- await RATE_LIMIT.put(key, `${currentTime}:1`)
- }
- } else {
- await RATE_LIMIT.put(key, `${currentTime}:1`)
- }
- // Proceed with the actual request handling here...
- return new Response('Request ok', { status: 200 })
- }
- ```
- In this script:
- - When a request is received, the script looks for the `X-Client-IP` header as the client identifier.
- - It then constructs a key for the KV store using this identifier.
- - The script checks the KV store for an existing record. If it exists, it parses the last request time and count.
- - It implements a simple rate limiting logic: if more than 10 requests are made within 60 seconds, it returns a 429 (Too Many Requests) status.
- - If the rate limit has not been exceeded, it updates the count (or resets it if the current time has moved past the 60-second window).
- - If the request is allowed, it continues to respond as usual. In a real-world scenario, you would replace the placeholder response with your actual request handling logic.
- Remember, Cloudflare KV updates are eventually consistent. This implementation is suitable for basic rate limiting but might allow requests slightly over the limit in high-traffic scenarios due to the eventual consistency model.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement