Create the account first last

published
edited
oct 18, 2026 · v2
reading
9 min
tags
backend, auth, state-machines

A multi-step signup usually goes like this: enter your email, type the code we sent, add your name, verify your phone, done. The obvious way to build it is to insert the user row on the first screen and update it at every step after.

That holds up until people stop halfway, and they do. The code is slow to arrive, the phone number has a typo, someone gets distracted. Now the users table has rows with an email but no phone, accounts that can log in but can't do anything, and people who come back a week later to hear that their email "already has an account" they never finished.

I rebuilt a flow like this so the account is created last. This post covers why, what the change actually guarantees, and where I would build it differently.

What counts as the account

By "the account" I mean the row the rest of the system trusts. It can log in, it shows up in admin tools, it counts in reports, and it can own data. Everything that happens before that row exists is collecting and checking information.

Why creating it first gets messy

When the row exists from step one, every later step updates a user who isn't really a user yet. Something has to mark the difference, so a status column appears, and every consumer of the table has to remember it. Login checks it. The admin list filters on it. The analytics query that counts signups has to know about it, and the one someone writes next quarter probably won't.

Retries get strange too. A person who abandoned signup and tries again runs into the unique constraint on a row they can't use. And the abandoned rows need a cleanup job that deletes old unfinished users without ever touching a real one.

None of this is hard on its own. The problem is that an unfinished workflow lives in the table everything else treats as the truth, so every reader pays for it.

Collect first, create once

The alternative is to keep the in-progress signup somewhere that is allowed to be temporary, and write the user only when every step is done. I'll call that place the signup session: a server-side record with an expiry, keyed by a random id in an HttpOnly cookie. It can be a row in a signup_sessions table or an entry in Redis. The choice matters later.

signup session: temporary, expires, holds everything so far email verify email details verify phone wrong code: retry email ✓ name phone ✓ password hash not a user yet: no half-users, can't log in, not in reports create (once) INSERT the user after create: session marked done with the user id, kept until it expires, so a retry still finds it UNIQUE(email) signup_id users table the real guarantee retry / double-click: signup_id matches, same answer, no second row second device, same email loses the race, rejected
every step lives in a temporary session; one write, at the end, behind a constraint
Step Data lives in Log in?
Email, verify email Session (expires) No
Details, phone, password Session (expires) No
Create users Yes

The server also owns the order of the steps. The client posts what it collected and renders whatever step it's told to render. That keeps the rules in one place, and it means a client can't skip phone verification by posting straight to the last endpoint.

signup/step.go
// Next picks the step to show, from the session alone.
// Validation, rate limits and code expiry are left out.
func Next(s *Session) Step {
	switch {
	case s.Email == "":
		return StepEmail
	case !s.EmailVerified:
		return StepVerifyEmail
	case s.Name == "":
		return StepDetails
	case !s.PhoneVerified:
		return StepVerifyPhone
	case s.PasswordHash == "":
		return StepPassword
	default:
		return StepCreate
	}
}

Every handler calls Next first, and the create handler refuses to run unless Next(s) == StepCreate. A verification only counts if the server recorded it in the session.

Secrets need a little thought, because the session now holds things that used to go straight into the users table. If the flow collects a password, hash it on the server as soon as it arrives and keep only the hash in the session. If the product allows it, you can go further and ask for the password together with the create step, so it goes from the request into the users row and never sits in a temporary store at all. Verification codes get the same treatment: store a hash of the code and an attempt count, not the code.

The create step has to be safe to repeat

Creating the account last gives you one structural guarantee: no user row exists until the flow is complete. It says nothing about the create step running twice, and it will. People double-click. A mobile client times out and retries a request the server had already committed.

Two properties are easy to blur here. Uniqueness means there is at most one user per email. A unique index gives you that, and the database enforces it no matter how requests race. Idempotency means that repeating the same request produces the same result. The unique index alone doesn't give you that. A retry of a create that already succeeded hits the constraint, and the person who just signed up is told their email is taken, by themselves.

The usual fix is to write the new user id back into the session and check it before inserting. That works only if the insert and the session write commit together. With the session in Postgres you can update it in the same transaction, and if the transaction locks the session row first (SELECT ... FOR UPDATE), so a double-click waits its turn, the fix is sound. With the session in Redis there's a gap: the insert commits, then the process dies or the response times out before the session is updated. The retry finds no id in the session, hits the constraint, and you're back to "email taken".

A version that works whichever store holds the session is to record, on the user row itself, which signup created it:

sql
-- users.email: unique index, stored normalized
ALTER TABLE users ADD COLUMN signup_id text;
-- signup_id stays null for accounts made other ways
signup/create.go
// Create inserts the user once per email. A retry
// from the same signup gets the same id back; any
// other signup gets ErrEmailTaken.
// Assumes Postgres at READ COMMITTED (the default).
func Create(ctx context.Context, tx *sql.Tx, s *Session) (UserID, error) {
	var id UserID
	err := tx.QueryRowContext(ctx,
		`INSERT INTO users
		   (email, name, phone, password_hash, signup_id)
		 VALUES ($1, $2, $3, $4, $5)
		 ON CONFLICT (email) DO NOTHING
		 RETURNING id`,
		s.Email, s.Name, s.Phone, s.PasswordHash, s.ID,
	).Scan(&id)
	if !errors.Is(err, sql.ErrNoRows) {
		return id, err // created, or a real error
	}
	// Email taken. If this signup took it, it's a retry.
	var owner sql.NullString
	err = tx.QueryRowContext(ctx,
		`SELECT id, signup_id FROM users WHERE email = $1`,
		s.Email,
	).Scan(&id, &owner)
	if err != nil {
		return 0, err
	}
	if owner.String != s.ID {
		return 0, ErrEmailTaken
	}
	return id, nil
}

Here is what that buys, precisely. The database guarantees one row per email. A retry from the same signup session gets the same user id, even when both requests run at once: the second insert waits on the unique index until the first commits, does nothing, and the SELECT that follows sees the committed row because each statement takes a fresh snapshot under READ COMMITTED. Under REPEATABLE READ or SERIALIZABLE, Postgres reports that conflict as a serialization failure instead, and the caller has to retry the transaction. A different session racing for the same email gets ErrEmailTaken. Since only the owner of the inbox can verify it, that's almost always one person on two devices or in two browsers. Two tabs in the same browser usually share one signup cookie, so they're the retry case, not the race.

Some of it rests on assumptions the code can't enforce. Emails have to be normalized the same way everywhere they're written, trimmed and lowercased for example, otherwise Ana@x.com and ana@x.com become two accounts. A unique index on lower(email) works too, but then the conflict target and the lookup have to use lower(email) as well, or Postgres won't match them to the index. If the create step writes more than one row, such as a profile or a default workspace, all of it belongs in the same transaction so a retry never finds a user without them. If phone numbers must be unique, they need their own constraint, and a violation there is a separate error that ON CONFLICT (email) doesn't cover. And "no half-users" only holds for paths that follow this rule. OAuth signups and admin-created accounts have their own code paths.

Once the create commits, don't delete the signup session. Mark it done with the new user id, start a logged-in session, and let the signup session expire on schedule. A retry needs a session to load: if you delete it and only the response gets lost, the retry finds nothing and the person is told their signup expired, right after it succeeded. So the create handler checks the mark first and, if it's there, returns the stored id without touching the users table. The mark answers retries that arrive after the create finished. signup_id answers the rest: two requests racing each other, or a mark that failed to save after the insert committed.

Checking the email early is a hint, not a guarantee

Many flows check at step one whether the email already has an account. It's good for UX, since the person learns early, but it doesn't replace the check at the end. Between step one and the create step, another device can finish signup with the same email. Only the constraint settles that, which is why Create handles ErrEmailTaken even though step one already looked.

The early check also leaks which emails have accounts. A way around that is to always answer "we sent you a code". If the email already has an account, the message that arrives says so and links to sign in or reset the password, instead of carrying a code. Only the owner of the inbox learns anything. By the time the create step can report a taken email, the person has proven they own that inbox, so saying it leaks nothing new. Whether that's worth it depends on the product: if your password reset page already reveals which emails are registered, hiding it on signup alone gains little.

What it costs

The signup session becomes something people depend on. If it expires mid-flow, they start over, so the expiry has to cover a slow SMS and a walk to find a phone. Something like 30 minutes, extended on every step, is a reasonable starting point. Don't make it so long that abandoned signups hold verified emails for days.

Where the session lives is a real trade-off. Redis cleans up after itself through TTLs, but it's another store to run, and when it's down signups stop. It also means you need signup_id, because you can't commit to Redis and Postgres atomically. A signup_sessions table in Postgres adds no new dependency and lets the create step mark the session done in the same transaction, but Postgres doesn't expire rows, so you're back to a cleanup job. It's a much safer one than before, though, because deleting an expired signup can never delete a real user. Either way, the session id now guards a verified email, so treat its cookie like an auth cookie: random, HttpOnly, Secure, SameSite.

You also lose the funnel view you used to get for free. With no row until the end, the users table can't tell you where people drop off. If you care about that, and most products do, record step events separately.

When to create the account early instead

If signup is one screen, an email and a password with verification afterwards, this pattern buys very little. Creating the user immediately with an email_verified flag is simple and common. The account is usable right away, and "unverified" is a small, well-understood state rather than a half-finished workflow.

If people need to resume on another device days later, or onboarding includes a review that takes days, such as identity checks or document uploads, a session with a 30-minute expiry is the wrong tool. That's durable workflow state. It deserves its own table, something like signup_applications, with its own status, history and retention, and the user row is still created at the end, when the application is approved. The principle is the same; the temporary place just lives longer and is taken more seriously.

Sometimes another system needs a stable id before signup finishes: referral attribution, a payment provider's customer record created during onboarding, an invite that has to link to the account. Then create the row early, but make the incomplete state hard to ignore. Give the rest of the system a view of complete users to read from, so that forgetting the status filter is the exception rather than the default. You're choosing to pay the cost described at the start of this post, so pay it in one place.

The principle

In a multi-step workflow, decide which write the rest of the system will believe. Keep everything before it somewhere that's allowed to be temporary, and make that one write idempotent, at the end, behind a constraint that can say no.

page history

  1. v2 · oct 18, 2026

    fixed the retry after a successful create (keep the session, marked done), the lower(email) note, the two-tabs example, and a password step in Next; clearer sketch

  2. v1 · oct 17, 2026

    published