Advertisement
Guest User

Rate Limiting Worker

a guest
Mar 17th, 2024
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | Source Code | 0 0
  1. 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.
  2.  
  3. 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`.
  4.  
  5. The worker script might look something like this:
  6.  
  7. ```javascript
  8. addEventListener('fetch', event => {
  9. event.respondWith(handleRequest(event.request))
  10. })
  11.  
  12. async function handleRequest(request) {
  13. const identifier = request.headers.get('X-Client-IP') // Or any header you prefer
  14.  
  15. if (!identifier) {
  16. return new Response('Identifier header missing', { status: 400 })
  17. }
  18.  
  19. const key = `ratelimit:${identifier}`
  20. const currentCount = await RATE_LIMIT.get(key)
  21. const currentTime = Math.floor(Date.now() / 1000)
  22.  
  23. if (currentCount) {
  24. const [lastTime, count] = currentCount.split(':').map(Number)
  25. if (currentTime - lastTime < 60 && count > 10) { // 60 seconds window, 10 requests limit
  26. return new Response('Rate limit exceeded', { status: 429 })
  27. }
  28.  
  29. if (currentTime - lastTime < 60) {
  30. await RATE_LIMIT.put(key, `${currentTime}:${count + 1}`)
  31. } else {
  32. await RATE_LIMIT.put(key, `${currentTime}:1`)
  33. }
  34. } else {
  35. await RATE_LIMIT.put(key, `${currentTime}:1`)
  36. }
  37.  
  38. // Proceed with the actual request handling here...
  39. return new Response('Request ok', { status: 200 })
  40. }
  41. ```
  42.  
  43. In this script:
  44.  
  45. - When a request is received, the script looks for the `X-Client-IP` header as the client identifier.
  46. - It then constructs a key for the KV store using this identifier.
  47. - The script checks the KV store for an existing record. If it exists, it parses the last request time and count.
  48. - 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.
  49. - 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).
  50. - 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.
  51.  
  52. 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