© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
4 replies
zobweyt

Implementing rate limiting for discord bot interactions with absolute expiration of items

I’m trying to create a simple and customizable
RateLimitAttribute
RateLimitAttribute
for interactions in Discord.Net using their preconditions.

I'm too confused about all the possibilities. So, how would you implement this? What decisions would you make and what data structures would you use?

Expected usage


[RateLimit(max: 2, period: TimeSpan.FromMinutes(1), ignore: Ignore.Owner | Ignore.DMs)]
[SlashCommand("ping", "Pings the bot.")]
public async Task PingAsync() => await RespondAsync("Pong!");
[RateLimit(max: 2, period: TimeSpan.FromMinutes(1), ignore: Ignore.Owner | Ignore.DMs)]
[SlashCommand("ping", "Pings the bot.")]
public async Task PingAsync() => await RespondAsync("Pong!");


Expected behavior


/ping
— Pong!
(count is now 1)
(count is now 1)


/ping
— Pong!
(count is now 2)
(count is now 2)


/ping
— Wait 60 seconds for limit to expire!

/ping
(30 seconds later)
(30 seconds later)

— Wait 30 seconds for limit to expire!

…
(30 seconds later)
(30 seconds later)

— Remove rate limit from store in background.

/ping
(any time later)
(any time later)

— Pong!
(count is now 1)
(count is now 1)


Wanted features:


- Users can define custom ignore policies: for instance, if you have a database with different roles like admins and regular users, you might want to apply rate limiting to all users but exclude admins.
- Users can access the store of rate limits: for example, EPIC RPG’s
/cd
/cd
command shows the cooldowns for each command per user.

Problems I’ve met


- Attributes require constant values:
TimeSpan
TimeSpan
 cannot be used directly. Instead, people use parameters specifying periods in seconds. Alternatively, a converter could be used with 
double period
double period
 and 
enum TimeMeasure
enum TimeMeasure
.
- Caching with absolute expiration:
IMemoryCache
IMemoryCache
's 
AbsoluteExpiration
AbsoluteExpiration
 simplifies caching implementation because it removes the rate limits right when they expire, but the keys there are strings and not generic types. Using
System.Threading.RateLimiting
System.Threading.RateLimiting
, it’s hard to display the exact remaining time until the limit expires.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

✅ Rate limiting no worky
C#CC# / help
17mo ago
Asp.net rate limiting
C#CC# / help
3y ago
How to configure rate limiting with Redis?
C#CC# / help
7mo ago
implement - basic rate limiting with a Dictionary
C#CC# / help
3y ago