SupabaseS
Supabase5mo ago
nsadeh

Race condition in insert

Hello, I have the following snippet:

const { data: prompt, error } = await supabase
    .from("prompts")
    .insert({ name, description })
    .select("*")
    .single();
  if (error) {
    throw new Error(error.message);
  }
  const { data: version, error: versionError } = await supabase
    .from("prompt_versions")
    .insert({
      prompt_id: prompt.id,
      content,
    });
  if (versionError) {
    throw new Error(versionError.message);
  }
  return prompt;
}


The important piece is to note that prompt_id on the prompt_versions table is a foreign key to the id column of prompts.

About 1 times out of 10 I get an error inserting the prompt version that it violates the foreign key constraint because the prompt doesn't exist. The prompt is however inserted successfully, Given the flakiness of the error, I'm positive it's a race condition.

I'm thinking this shouldn't happen since the routine to insert the prompt completes successfully and is awaited. Please let me know if I'm missing something here.
Was this page helpful?