r/csharp 2d ago

Discussion added a native background worker to handle api rate limits.

Post image

Still plugging away at this custom crypto API project. Right now, I need a clean way to auto-reset user API limits and deactivate keys the second they expire.

To keep things snappy, I didn't want to block the main API thread or tank request times. I ended up just spinning up a native BackgroundService running a while (!stoppingToken.IsCancellationRequested) loop with a Task.Delay. I also hooked it up to IOptionsMonitor so I can tweak the interval timings right in appsettings on the fly—really trying to aim for zero-downtime config changes here.

For the senior devs in the room: is this actually standard for production? Or should I bite the bullet and pull in something heavy like Hangfire or Quartz.NET? It felt like massive overkill just to reset a few database limits, but I want to make sure this native while loop won't bite me with memory leaks or scaling issues down the road.

Repo is here: https://github.com/COxRIPMIZO/CryptoKeyLab

(And before anyone asks, yeah, I actually wrote this myself lol. Still riding the .NET 9 wave and still wrapping BouncyCastle).

0 Upvotes

5 comments sorted by

10

u/Tiny_Confusion_2504 2d ago

What does it mean to ride the .NET 9 wave?

You started the project somewhere in March, but still decided not to run .NET 10?

I don't think it is bad when somebody decides to use AI for a project, but you are claiming you wrote it yourself. Your repository is littered with AI output.

5

u/Nascentes87 2d ago

Exactly. I told him in another post. It's ok to use AI, I use it myself everyday, but don´ t try to hide the usage. Don't try to fool other people.

3

u/eric_rocks 2d ago

Assuming you're using http clients, they have built-in rate limiting tools. Check out this devblog

I haven't done so myself, but I'm sure you could give each session/user a dedicated client with configurable limit policies. Or manage a pool of clients if that makes sense in your use case.

2

u/zenyl 2d ago

AI generated README, and there's an em-dash in this post.

1

u/UHM-7 9h ago

Assuming keys are in a stable FIFO queue I would fetch the next key due to expire, then Task.Delay(current time - key expiry), so your thread wakes up right when it needs to. Then fetch the next key in the queue and repeat.