How Arcjet Protects Your Website from Spam Users and Bots Using TokenBucket
sudip khatiwada

sudip khatiwada @sudiip__17

About: Frontend Developer | React & Next.js Enthusiast | Passionate about building user-friendly web apps. Always learning, sharing, and growing. Open to remote/hybrid opportunities!

Location:
Sudurpaschim, Nepal
Joined:
Aug 3, 2025

How Arcjet Protects Your Website from Spam Users and Bots Using TokenBucket

Publish Date: Aug 23
0 0

Every day, websites face millions of automated attacks from spam bots, scrapers, and malicious users. These unwanted visitors consume server resources, skew analytics, and can even crash your application. Traditional rate limiting solutions often fall short, but Arcjet's TokenBucket algorithm provides intelligent protection that adapts to real traffic patterns.

In this guide, you'll learn how to implement Arcjet protection using TokenBucket rate limiting to safeguard your Node.js applications from spam and bot traffic.

What is Arcjet and Why Use It?

Arcjet is a modern security platform that combines multiple protection layers including bot detection, rate limiting, and attack prevention. Unlike basic rate limiters, Arcjet uses machine learning to distinguish between legitimate users and malicious traffic.

The platform offers three core protection features:

  • Shield: Blocks common attack patterns and suspicious requests
  • DetectBot: Identifies and filters automated bot traffic
  • TokenBucket: Implements intelligent rate limiting with burst capacity

Understanding TokenBucket Rate Limiting

Think of TokenBucket like a water bucket with a small hole. Water (tokens) drips in at a steady rate, but users can take gulps (make requests) as long as water remains. This approach allows legitimate users to make quick bursts of requests while preventing sustained spam attacks.

Here's how TokenBucket parameters work:

  • Capacity: Maximum tokens the bucket can hold
  • Refill Rate: How many tokens are added per interval
  • Interval: Time between token refills
  • Requested: Tokens consumed per request

Setting Up Arcjet Protection

Step 1: Configure Arcjet Rules

Create your main Arcjet configuration file (arcjet.js):

import arcjet,{shield, detectBot, tokenBucket} from "@arcjet/node";
import {ARCJET_KEY} from "./env.js";

const aj = arcjet({
    key: ARCJET_KEY,
    characteristics: ["ip.src"],
    rules: [
        shield({ mode: "LIVE" }),
        detectBot({
            mode: "LIVE",
            allow: [
                "CATEGORY:SEARCH_ENGINE",
            ],
        }),

        tokenBucket({
            mode: "LIVE",
            refillRate: 5, // Refill 5 tokens per interval
            interval: 10, // Refill every 10 seconds
            capacity: 10, // Bucket capacity of 10 tokens
        }),
    ],
});

export default aj;
Enter fullscreen mode Exit fullscreen mode

This configuration creates a TokenBucket that refills 5 tokens every 10 seconds with a maximum capacity of 10 tokens. Users can make up to 10 rapid requests, then must wait for the bucket to refill.

Step 2: Create Protection Middleware

Build middleware to integrate Arcjet protection (arcjet.middleware.js):

import aj from '../config/arcjet.js'

const arcjetMiddleware = async(req, res, next) => {
    try {
        const decision = await aj.protect(req, {requested : 1});

        if (decision.isDenied()) {
            if (decision.reason.isRateLimit()) return res.status(429).json({ message:'Rate limit exceed' });
            if (decision.reason.isBot()) return res.status(403).json({ message:'Bot detected' });
        }
        next();
    } catch (error) {
        console.log(`Arcjet middleware error : ${error}`);
        next(error);
    }
}

export default arcjetMiddleware;
Enter fullscreen mode Exit fullscreen mode

The middleware requests 1 token per API call and handles two scenarios:

  • Rate limiting: Returns HTTP 429 when tokens are exhausted
  • Bot detection: Returns HTTP 403 for identified bots

How TokenBucket Prevents Spam and Bot Attacks

Burst Protection

Legitimate users occasionally need to make multiple quick requests (loading a dashboard, submitting forms). TokenBucket allows these natural usage patterns while blocking sustained automated attacks.

Adaptive Rate Limiting

Unlike fixed rate limits, TokenBucket accumulates unused capacity. If a user hasn't made requests recently, they can use stored tokens for legitimate bursts without hitting limits.

Resource Conservation

By blocking excessive requests early, TokenBucket prevents server overload and maintains performance for legitimate users.

Integration Best Practices

Choose Appropriate Token Values

  • High-traffic APIs: Increase capacity and refill rate
  • Sensitive endpoints: Use lower values for stricter protection
  • Public APIs: Balance accessibility with protection

Monitor and Adjust

Track your application metrics to fine-tune TokenBucket parameters:

# Monitor rate limit hits
curl -I https://your-api.com/endpoint
# Look for HTTP 429 responses in logs
Enter fullscreen mode Exit fullscreen mode

Whitelist Legitimate Bots

The detectBot rule allows search engines while blocking malicious crawlers. You can expand the allowlist for specific legitimate services.

Real-World Impact

Implementing Arcjet TokenBucket protection typically results in:

  • 60-80% reduction in spam traffic
  • Improved server response times for legitimate users
  • Lower bandwidth costs from blocked malicious requests
  • Better analytics accuracy with cleaner traffic data

Conclusion

Arcjet's TokenBucket algorithm provides intelligent rate limiting that adapts to real user behavior while effectively blocking spam bots and malicious traffic. By combining bot detection, attack prevention, and adaptive rate limiting, you create a robust defense system for your Node.js applications.

The flexible token-based approach ensures legitimate users aren't penalized while maintaining strong protection against automated attacks. Start implementing Arcjet protection today to secure your applications and improve user experience.

Ready to protect your website? Install Arcjet and configure TokenBucket rate limiting to stop spam users and bots before they impact your application performance.

Get started with Arcjet today: https://arcjet.com/

Comments 0 total

    Add comment