Go limit service time per user

Photo by Erik Mclean on Unsplash

Go limit service time per user

Joash Xu
·Jan 7, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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.

Solution

This solves the problem where you need to limit processing time for every user.

Key takeaways

  1. Use a similar pattern as the previous problem (limit service to 10 seconds per request), where I use a select block wrapped in a for-loop.
  2. Use time.Tick to 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.
  3. To keep track of the accumulated time used, you should use mutex via the sync.Mutex package. In this problem, every time you receive a time tick, set a lock and then update the TimeUsed variable. 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.
 
Share this