Deutsch
Error messageSupabase · Postgres

Fix “duplicate key value violates unique constraint” in Supabase

Why Supabase says duplicate key value violates unique constraint: a profile created twice, a retried webhook or double click, or an id counter that fell behind.

The message you seePostgres · 23505

duplicate key value violates unique constraint "profiles_pkey"

By Tim GeithnerPublished 5 min read

Short answer

A row with the same key already exists, so Postgres refused the new one. In apps built with Lovable, Bolt or Cursor the usual causes are a profile created twice (once by a sign-up trigger, once by the app), a request that ran twice (a retried Stripe webhook or a double-clicked button), or an id counter that fell behind after an import. Update instead of inserting, make repeated requests do nothing, or move the counter. Never drop the constraint, and never open the update policy to make an upsert work.

Ask an AI about this page:ChatGPTClaude

On this page

A primary key or a unique column only allows each value once. Your insert used a value that is already taken, so Postgres refused it with error code 23505, and the Supabase API answers with HTTP 409. Nothing was saved. Most of the time the constraint is doing you a favour: it stopped a second profile, a second payment booking or a second copy of the same row.

The constraint name tells you which value clashed. profiles_pkey is the primary key of profiles, so a profile with that id already exists. A name like profiles_username_key means the username column. Outside row level security the details line also shows the value, for example Key (id)=(1) already exists.

Find your cause in 30 seconds

What happenedMost likely cause
Right after sign-up, on profiles_pkeyThe profile is created twice
In a webhook, a payment flow or after a double clickThe same request ran twice
On ..._pkey for a table where you never send an idThe id counter is behind

We ran all three on Postgres with Supabase’s roles before writing this page. The profile setup is the one from Supabase’s docs: a trigger creates the profile when the user signs up.

The table and trigger used on this page
create table public.profiles (
  id uuid primary key references auth.users (id) on delete cascade,
  username text,
  updated_at timestamptz not null default now()
);

alter table public.profiles enable row level security;

create policy "Users can read their profile"
  on public.profiles for select to authenticated
  using ((select auth.uid()) = id);
create policy "Users can create their profile"
  on public.profiles for insert to authenticated
  with check ((select auth.uid()) = id);

create function public.handle_new_user()
returns trigger
language plpgsql
security definer set search_path = ''
as $$
begin
  insert into public.profiles (id) values (new.id);
  return new;
end;
$$;

create trigger on_auth_user_created
  after insert on auth.users
  for each row execute function public.handle_new_user();

The three causes

1. The profile is created twice

The trigger already created the profile at sign-up. Then the onboarding form, often added later by the AI builder, inserts it again:

VulnerableThe onboarding form, after sign-up
await supabase.from("profiles").insert({ id: user.id, username });

The second insert hits profiles_pkey. The same happens if two parts of the app both create the profile, for example a layout and a page that each run on first load.

2. The same request ran twice

Stripe retries a webhook when your endpoint answers slowly or with an error, and its docs say an endpoint can receive the same event more than once. A user double-clicks “Save”. A flaky connection resends a request. If a unique constraint protects the table, the second attempt fails with this message. That is good: without the constraint, the duplicate would have been saved. The fix is to make the second attempt do nothing on purpose, which is called idempotency.

3. The id counter is behind

Tables with generated by default as identity or serial ids take the next id from a counter, a sequence. If you import rows with their own ids, from a CSV or another database, the counter does not move. The next insert gets id 1, which already exists:

VulnerableAn imported table whose id counter is behind
create table public.items (
  id bigint generated by default as identity primary key,
  name text not null
);

insert into public.items (id, name)
values (1, 'Imported A'), (2, 'Imported B'), (3, 'Imported C');

The next insert into public.items (name) values ('New') fails with duplicate key value violates unique constraint "items_pkey".

How to fix it

For cause 1, keep the trigger as the only place that creates profiles, and let the form update the existing row. Users need an update policy for that, tied to their own row:

SafeFix: let users update their own profile
create policy "Users can update their profile"
  on public.profiles for update
  to authenticated
  using ((select auth.uid()) = id)
  with check ((select auth.uid()) = id);
SafeThe onboarding form, fixed
await supabase.from("profiles").update({ username }).eq("id", user.id);

.upsert({ id: user.id, username }) works too once this policy exists. Without it, an upsert on an existing row fails with the row level security error, the variant that ends in (USING expression).

For cause 2, let the database decide whether a request is new. Record a key for each request, such as the Stripe event id, in a table where it is the primary key, and use on conflict do nothing:

SafeFix: a table that remembers handled requests
create table public.handled_requests (
  key text primary key,
  handled_at timestamptz not null default now()
);

alter table public.handled_requests enable row level security;
revoke all on table public.handled_requests from anon, authenticated;
In the handler: claim the key first
insert into public.handled_requests (key)
values ($1)
on conflict (key) do nothing
returning key;

If this returns a row, the request is new: do the work. If it returns nothing, the request was already handled: answer with success and stop. Do both in the same transaction as the work, so a failed attempt leaves no key behind and the retry can finish it. The non-idempotent Stripe webhook fix shows the complete function. For double clicks, also disable the button while the request runs, and treat error code 23505 as “already saved”.

For cause 3, move the counter past the highest id:

SafeFix: move the id counter past the highest id
select setval(
  pg_get_serial_sequence('public.items', 'id'),
  (select max(id) from public.items)
);
Fix the duplicate key error without opening the table

My Supabase app fails with “duplicate key value violates unique constraint” on the constraint named in the error. Find the constraint in the migrations and every place that inserts into that table, including triggers on auth.users, edge functions and webhooks. Then fix the cause: if a trigger already creates the row, change the app code to update it instead of inserting, and add an update policy for the authenticated role with using and with check both (select auth.uid()) = the owner column. If the same request can arrive twice (webhooks, retries, double clicks), store a request key in a table with that key as primary key, insert it with on conflict do nothing in the same transaction as the work, and skip the work when nothing was inserted. If an id sequence is behind after an import, reset it with setval to the highest id.

Do not drop primary keys or unique constraints, do not add policies with true, do not use the service role key in client code and do not edit existing migrations. Show me the migration and the code change before applying them.

Check that the fix works

In the SQL Editor, act as a signed-in user inside a transaction and save the profile twice, the way the fixed form does. Use a real user id from Authentication → Users:

Check: save the profile twice as the user
begin;
set local role authenticated;
set local request.jwt.claims = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated"}';
update public.profiles set username = 'ann' where id = '11111111-1111-1111-1111-111111111111' returning id, username;
update public.profiles set username = 'ann' where id = '11111111-1111-1111-1111-111111111111' returning id, username;
rollback;

Both updates return the same single row and nothing fails. Then change the id in the where clause to another user’s id: the update must return no row, because the policy only lets users change their own profile. For webhooks, deliver the same test event twice and check that the work happened once. The guide to testing RLS policies has more checks to run before launch.

Frequently asked questions

Can I just remove the unique constraint?

No. The constraint is the only thing that stops the same payment from being booked twice or a user from getting two profiles. Without it, the duplicate is saved silently and your app shows or charges the wrong thing later. Keep it and handle the conflict.

Should I just use upsert everywhere?

Only where overwriting is what you want, such as saving a profile form. An upsert needs an update policy, and that policy must check the owner, or any user can overwrite any row. For events that must happen once, like a payment, use on conflict do nothing and stop when nothing was inserted.

Why does the error in my app not show which value was duplicated?

When the table has row level security, Postgres leaves the value out of the details. The constraint name still tells you where to look: tablename_pkey is the primary key, tablename_column_key is a unique column. Through the Supabase API the request answers with HTTP 409.

The error appears on a table where I never send an id. Why?

The id counter is behind. That happens after you imported rows with their own ids, for example from a CSV or another database. The next generated id already exists. Move the counter past the highest id, as shown on this page.

Sources

  1. 1.Constraints: Unique Constraints and Primary Keys — PostgreSQL Documentation
  2. 2.INSERT: ON CONFLICT clause — PostgreSQL Documentation
  3. 3.Sequence Manipulation Functions — PostgreSQL Documentation
  4. 4.Errors — PostgREST Documentation
  5. 5.Receive Stripe events in your webhook endpoint — Stripe Docs
  6. 6.User Management — Supabase Docs

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt