I have a service which provides an endpoint that fetches from another service, saves, and returns an record. Here are the details:
- The caller calls the endpoint using an identifier (say a customer's student ID number)
- The service checks DB for that student ID. If no record that has not expired is found, the server calls an outside service to fetch the record. (which costs money per call)
- The record is saved in DB with timestamp, and returned
- If a non-expired record with the same ID is found in the DB, that saved record is returned instead.
So basically it's caching the records with an expiration date. The problem is that there are cases where the same ID is getting called for multiple times within a split second. They happen too close to each other so the fetch and save operation by the first call has not finished before the second call comes. As a result, duplicate calls are fired to the external service and duplicate records are in the DB.
So is there any way to cache this type of duplicate calls. Would memory cache be a good candidate for solving this problem?