Ratelimiting on Your SaaS made easy with Unkey

Ratelimiting on Your SaaS made easy with Unkey

ยท

5 min read

Hey folks, I know I've been writing a lot of blogs mostly about OSS projects, but you all know that OSS projects are the heart of software engineering. They are secure and maintained by many people. In this blog, I'll introduce a new OSS project called Unkey. They are already popular, but if you're not aware, Unkey provides a simple and easy way to rate limit your application in minutes. Yes, it's true! I'll show you how to do that in this blog. So, buckle up, here we go!

So Iโ€™ll will be implementing Unkeyโ€™s famous feature of ratelimiting in this project they offer various other features too like

  1. Temporary keys : Temporary API Keys are API Keys that expire after a certain amount of time. They are useful for when you want to give a user access to your API for a limited amount of time. For example, you might want to give a user access to your API for 1 hour, or 1 day, or 1 week. You can do this by creating a temporary API Key that expires after a certain amount of time.

  2. Usage limited Keys : Sometimes you would like to create an api key and automatically invalidate it after a certain number of uses.

    Example: You are selling API access and a customer has purchased 1000 api requests from you.Unkey allows you to set/update usage limits on individual keys and we take care of invalidating a key after it has reached its limit.

  3. Refill : This feature is useful for creating an API key that automatically refills daily or monthly. Daily refills trigger each night at midnight, while monthly refills are triggered on the first day of each month.

    Example: Suppose you are selling API access, and a customer has purchased 1000 API uses per month. On the first day of the month, the 1000 uses will be refilled for that key.

  4. Analytics : Unkey offers both per key and per API analytics that allow you to drive business decisions.

  5. And many more ..

Let's Build! ๐Ÿš€

I will be implementing rate limiting in my quote generator application, which I created using Next.js 15.

1. Setup the Project using NPM

npx create-next-app@latest rate-limited-quotes
cd rate-limited-quotes

2. The Magic Ingredient: Unkey Setup โœจ

Install Unkey:

npm install @unkey/ratelimit

Now, here's where the magic happens. Create lib/unkey.ts:

typescriptCopyimport { Ratelimit } from '@unkey/ratelimit'

export const unkey = new Ratelimit({
  rootKey: process.env.UNKEY_API_KEY,
  namespace: 'quote.generator',
  limit: 5,              // 5 requests allowed
  duration: '1m',        // per 1 minute
  async: true,
})

Here is the text editor Image for ref

This tiny piece of code is like setting up a friendly bouncer who:

  • Remembers each visitor (by IP address)

  • Allows 5 entries per minute

  • Politely asks others to wait when the limit is reached

3. The Quote API: Where Rate Limiting Shines ๐ŸŒŸ

Let's create our API endpoint (app/api/quote/route.ts):

typescriptCopyexport async function GET(request: NextRequest) {
  const ip = getClientIp(request)
  const rateLimitResponse = await unkey.limit(ip)

  if (!rateLimitResponse.success) {
    return NextResponse.json(
      { 
        error: 'Whoa there! Time to take a breather. Try again in a minute! ๐Ÿ˜…',
        remaining: 0,
        reset: rateLimitResponse.reset
      }, 
      { status: 429 }
    )
  }

  // Return a random quote...
}

here is my route.ts file looks like

This is where Unkey really shines. With just a few lines of code, we've added:

  • IP-based rate limiting

  • Automatic rate tracking

  • Reset timers

  • Remaining requests counter

No Redis setup, no complex calculations, no headaches! ๐ŸŽ‰

4. Making It Pretty: The UI Layer ๐Ÿ’…

We used shadcn/ui to create a beautiful interface that shows:

  • The current quote

  • Remaining API calls

  • Elegant error states

  • Loading animations

<Card>
  <CardHeader>
    <CardTitle>Your Daily Dose of Wisdom</CardTitle>
  </CardHeader>
  <CardContent>
    {quote && (
      <blockquote>
        "{quote.text}" - {quote.author}
      </blockquote>
    )}
    <div>
      Calls remaining: {quote?.remaining || 0}
    </div>
  </CardContent>
</Card>

Here is mine

Let's run the project from the terminal to see the code and output in action below.

We made it guys the output might not look the same but still you have at least made something with Unkey.

The Cool Features can be added ๐ŸŽจ

  1. Smart Rate Limiting: Like a traffic light for your API

  2. Real-time Feedback: Users know exactly how many requests they have left

  3. Elegant Error Handling: No angry red error messages, just friendly reminders

  4. Smooth Loading States: Because waiting should be pretty

Behind the Scenes: How Rate Limiting Works ๐ŸŽญ

Think of Unkey's rate limiting like a nightclub with a strict policy:

  1. Each visitor (IP address) gets 5 VIP passes (requests)

  2. These passes refresh every minute

  3. Try to enter without a pass? You'll get a friendly reminder to wait

The best part? Unkey handles all this automatically. You don't need to:

  • Set up a database

  • Write complex counting logic

  • Handle race conditions

  • Manage distributed systems

Why This Matters ๐ŸŽฏ

Rate limiting isn't just about protecting your API; it's about:

  1. Fair Usage: Everyone gets their fair share

  2. Cost Control: Prevent abuse and control costs

  3. Better Performance: Keep your API running smoothly

  4. Happy Users: Clear feedback = happy users

Tips and Tricks ๐Ÿ’ก

  1. Use Clear Error Messages: Help users understand what's happening

  2. Show Remaining Calls: Let users pace themselves

  3. Add Visual Feedback: Loading states and error messages should be clear

  4. Plan Your Limits: Choose rate limits that make sense for your use case

Conclusion ๐ŸŽฌ

Building a rate-limited API doesn't have to be complicated. With Unkey and Next.js 15, we've created a robust, user-friendly quote generator that:

  • Protects our API from abuse

  • Provides a great user experience

  • Requires minimal setup and maintenance

The best part? You can adapt this pattern for any API you build. Whether it's a weather app, a social media API, or the next big thing - you now have the tools to implement professional-grade rate limiting with ease.

Ready to Build? ๐Ÿš€

The complete code is available on GitHub. Give it a star if you found this helpful!

and you can even check it out here

Remember: Good APIs are like good bouncers - firm but fair, clear about the rules, and always professional! ๐Ÿ˜‰

Did you find this article valuable?

Support K5LO7H's Blog by becoming a sponsor. Any amount is appreciated!

ย