Video in progress

In a system split across several databases or shards, how do you guarantee a globally unique value like `username` or email?

Each shard knows about uniqueness only within itself. For global uniqueness you need a separate "reservation" table (in one place, with a unique key), or you make the unique value the shard key. Because a write touches two places, I design it as reservation first, then the main record, and cleanup on failure.

📖 Answer

Users are sharded by user_id. UNIQUE (email) works within each shard, but two people can sign up at the same time with the same email on different shards.

The options:

  1. Routing by the unique value. Make the email the shard key: then the same email always lands on one shard and a plain unique works. But it's awkward if the user's other data is needed by user_id.

  2. A global reservation table. A small, separate database (or a coordinator shard):

CREATE TABLE email_claim (
    email_normalized text PRIMARY KEY,
    user_id          bigint NOT NULL,
    status           text   NOT NULL,     -- PENDING / ACTIVE
    claimed_at       timestamptz NOT NULL DEFAULT now()
);

The sign-up flow:

  1. INSERT INTO email_claim (... 'PENDING'): a unique violation means the email is taken.
  2. Create the user on its own shard.
  3. Mark the claim ACTIVE.

If step 2 fails, a PENDING claim is left hanging; a background job checks old PENDING claims and cleans them up. This is a small version of a saga, without 2PC.

  1. An external system. Sometimes the identity provider (Keycloak and so on) does this job for you.

Normalization matters too: rules like lower(trim(email)), Unicode and Gmail dots are defined in one place, otherwise Ali@x.uz and ali@x.uz get reserved twice.

The reservation table adds one more round trip to the write path and a single point of failure, but it's small and used only at sign-up and on changes, so we usually accept that price.