Serringer's avatar

File upload race conditions

Hi we have a front end that uploads a file to the server, each of these uploads happens simultaneously via AJAX. This triggers a function which finds an order that the file has to be associated to, and enters the files id into a table. But since there are several files being uploaded at the same time the table that contains these id's are being overwritten, which results in not all files are associated with the order in this way. LockForUpdate does only seem to make the problem worse with more files that are not put into the table. The reason for the saving the file in the table is that we need the different files in different situations, which the order table contains currently.

0 likes
3 replies
lostdreamer_nl's avatar

why are you not sending the order_id with the uploaded file?

Can you show some of the code that you have now so it's easier to see what could be changed?

Serringer's avatar
public function file(Request $request, $order)
    {
        $order = Order::where('unik', $order)->lockForUpdate()->first();

        $file = File::store($request->file('file'), $order);

        if ($request->has('ordered_by')) {
            $ordered_by = User::whereUnik($request->ordered_by)->first();
            $order->ordered_by = $ordered_by->unik;
        }

        if ($request->has('order_nr')) {
            $order->order_nr = $request->order_nr;
        }
        $order->save();
        $order->addFileToServices($file, $request->has('client') ? $request->client : null);

        return response(['message' => 'ok', 'file' => $file->unik], 200);
    }

the file is transferred via Dropzone, which uploads parallel

lostdreamer_nl's avatar

I really dont understand this part: "But since there are several files being uploaded at the same time the table that contains these id's are being overwritten"

Why not use an incrementing ID in that table, you upload the file, insert it into the table, get a unique ID back, and do the rest with that.

Also, what is happening in this method? :

$order->addFileToServices($file, $request->has('client') ? $request->client : null);

If that is where you save some id to the order, then that's probably where something is going wrong.

Please or to participate in this conversation.