TRPC ratelimiting endpoints
I am currently having some problems with a race condition in my TRPC nextJS api.
Essentially what is happening is I have a
enforceGuildPermissions
method, which basically checks if the user who is making the request has permission to get the data for that guild.
The data is stored in my Redis cache for 3 seconds. This works okay sometimes, but other times because there is 3-4 different trpc requests running for a single page which are guild, role and channel. It causes the last request (channel) to get rate limited by the discord API because they are all running concurrently, this means it doesn't give my caching code chance to update it before the next one runs.
middleware route procedure:
12 Replies
function which needs to be ratelimited (using the redis cache)
A big band aid fix would be to just add an artificial wait:
But obviously this is not very elegant..
bump
This isnβt really a tRPC problem, caching and rate limiting is hard
Probably simplest to recognise rate limits and retry the task though
You can dedupe the call to discord
Have a fn to do it passed down through the context and memoize the promise
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
try running that
Hi, thank you for the response. But I'm not sure I follow. Since this is hosted on serverless infrastructure (vercel), I don't think this is possible to use a in memory cache to stop this from happening? I may be misunderstanding your solution though.
You can use the above to make sure two calls to discord aren't done within the same request
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
if you use that the thing will only be called once per request
so batching will be deduped
if you have many users you gotta do something fancier where you can synthesise the promise in redis or something
Thank you very much, when I get some time I shall look at this.
@alex / KATT hi, I had time to do this now. Thank you SO much! This issue was slowing my site down alot, and now it is fast once again!
But just so I understand, why does this solution not scale? You say I may have to deal with the promise in redis? Why is using memo not okay?
I havenβt looked at the solution, but (as a thought experiment) what happens if you have 2, 3, 15 parallel instances of the API running? (Horizontal scaling)
Hmm, yes okay. I see what you are saying. This depends on vercel runs nextjs api endpoints, im not entirely sure. For now, this is working just fine. But I should look into this just encase. Thank you very much for the help π