How to limit requests per USER in ServletAPI (Spring MVC)


How to limit requests per USER in ServletAPI (Spring MVC)

How can I allow only a one request to micorservice method with specific URL @PathVariable per User.
My Controller
@RequestMapping(value = "/rest/product", produces = "application/json;charset=UTF-8")
public class ProductRestController {
    ProductService productService;

    ProductAsm productAsm;

    @RequestMapping(value = "/ID/{ID}", method = RequestMethod.GET)
    public ResponseEntity getProductID(@PathVariable("ID") Long ID, @AuthenticationPrincipal User) {

        Product product = productService.getProduct(ID);
        if (product == null)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        return new ResponseEntity<>(productAsm.toResource(product), HttpStatus.OK);

For example :

first request /rest/product/ID/2231 allowed for USER(with login="xaxa" )
second request /rest/product/ID/2545 allowed for USER(with login="xaxa" )
thirdth request /rest/product/ID/2231 not allowed for USER(with login="xaxa" )

Which is the best way to implement this functionality?(Have I to keep this URL request with User login in DB or there is already solutions)


Answer 1:

You could use AOP and implement your own aspect that would be called Before your Rest Endpoint method.

This pointcut would read ID provided in a request and would try to find a Lock corresponding with this ID. Then the usual – try to access resource and potentially wait.

Implementation could base on Guava’s Striped class – at least for the start.

There are several problems that need to be taken into consideration:

  1. Striped could be replaced with some LRU Cache for better memory management.
  2. You would of course have to provide synchronization for the case when the same ID is accessed simultaneously by two requests.
  3. It would work only for an application deployed on a single node.
  4. It would not be very good approach performance-wise. Depending on your traffic this may be an issue.