In order to add the free tier for smudge.ai, I needed a way to limit the number of commands free users could run over a set period of time. Existing N

Building a rate limiter in TypeScript (and some Lua)

submited by
Style Pass
2024-04-19 21:00:04

In order to add the free tier for smudge.ai, I needed a way to limit the number of commands free users could run over a set period of time. Existing Node.js rate limiters didn’t quite fit the bill (more on that below), so I rolled my own.

I used Redis as the data store. One catch for a TypeScript dev like myself: Redis scripting is all Lua. The approach I took was to prototype using the language I know, then port the solution to Lua once I had proved that the logic was sound. While the specific problem of building a custom rate limiter is fairly niche, defining custom Redis commands that you can call from Node.js is quite useful! With that in mind, I’m sharing what I’ve learned about this so far and hope you get something out of it, too.

In order to limit free tier users to n commands per day, we first need to answer the question: what is a day? Seems simple, but there are some nuances.

Leave a Comment