Photo by Erik Mclean on Unsplash
Go limit service time per user
·Jan 7, 2022·
1 min read
In this problem, you are given a video processing service with a freemium tier. Everyone will be given 10 seconds of free processing time. If you are not a paying user, the service will kill your process after 10 seconds.
There are two variations for this problem. You can limit every 10 seconds for every request or limit 10 seconds for every user accumulated.
This article will discuss the first one, limiting every user to 10 seconds.
This solves the problem where you need to limit processing time for every user.
- Use a similar pattern as the previous problem (limit service to 10 seconds per request), where I use a
selectblock wrapped in a for-loop.
time.Tickto write to a channel every second. And then, we check whether the user has reached ten seconds. Return the function if the user is not a premium user and has used all ten seconds.
- To keep track of the accumulated time used, you should use mutex via the
sync.Mutexpackage. In this problem, every time you receive a time tick, set a lock and then update the
TimeUsedvariable. Check if the user has used up their ten seconds. If they have and are not premium, return false to mark that the process has to be killed.