Calling external API once and cache it
<p>I am using a 3rd party API for flight data using a curl call.
After I made the curl call, I parse the data and insert it into a db for caching.(API Calls are not free)</p>

<p>Whenever multiple users make the same request for a flight the same time, it calls the external API multiple times, because it takes some time to make the curl call parse the data and then insert into the db.
So all requests check the db, realise it's not in there, and start calling the external API. When finished, it realises it already has the flight data and stops making a db insert call.</p>

<p>How do I prevent this using best practices?</p>

<pre><code>    $flightnum = $_POST['flightnum'];
    if (isFlightInDB($flightnum))
        return json_encode (getFlightFromDb ($flightnum));
    else {
        $flight = callFlightApiAndCache($flightnum);
        return json_encode($flight);
    }
</code></pre>