Skip to main content

Bun

Step-by-step Bun rate limiting tutorial using @unkey/ratelimit. Build a Bun HTTP server that throttles abusive clients with no Redis required.
2 min read

What you'll build#

A Bun HTTP server with rate limiting. Users who exceed the limit get a 429 response.

Time to complete: ~3 minutes

Prerequisites#

Create a Bun project#

Install the SDK#

Add your root key#

Create a .env file:

.env

Create your server#

Replace index.ts:

index.ts

Run your server#

Test it#

First 10 requests return data. Requests 11+ get:

What's in the response?#

limiter.limit() returns:

FieldTypeDescription
successbooleantrue if allowed, false if rate limited
remainingnumberRequests left in current window
resetnumberUnix timestamp (ms) when window resets
limitnumberThe configured limit

Multiple rate limiters#

Create different limiters for different use cases:

index.ts

Next steps#

Troubleshooting#

Rate limit not applying?
  • Verify UNKEY_ROOT_KEY is in your .env file - Use Bun.env.UNKEY_ROOT_KEY (not process.env) - Check your root key has ratelimit.*.limit permission
Environment not loading?

Bun loads .env automatically. Make sure the file is in your project root and restart the server.