Skip to content

Unique username with DCB

Global uniqueness without sagas, using a read and a conditional append

Let’s build a registration flow where usernames are globally unique. No sagas. No compensation. Just DCB.

The naive version is “read if taken, then append if not.” Two requests can both read “free” and both insert. DCB closes that hole: you read tagged events up to a position, then append only if nothing matching slipped in after that position.

Request A Request B
│ │
├ readByQuery ──▶ empty │
│ ├ readByQuery ──▶ empty
│ │
├ append(condition) ──▶ OK │
│ ├ append(condition) ──▶ FAIL
▼ ▼
UserRegistered "username taken"
  • A UserRegistered event with a username: tag
  • A DCB read that checks for collisions
  • A conditional append that enforces uniqueness
type UserRegistered = {
type: 'UserRegistered';
data: {
userId: string;
username: string;
};
tags: string[];
};
const tag = `username:${username.toLowerCase()}`;
const query = {
items: [
{
types: ['UserRegistered'],
tags: [tag],
},
],
};
const { events, lastPosition } = await eventStore.readByQuery({
query,
after: 0,
});

If events.length > 0, the username is already taken.

const event: UserRegistered = {
type: 'UserRegistered',
data: { userId, username },
tags: [tag],
};
await eventStore.append([event], {
failIfEventsMatch: query,
after: lastPosition,
});

If someone else registers the same username after you read, the append fails. That is the boundary doing its job.

import { isAppendConditionError } from '@delta-base/server';
try {
await eventStore.append([event], {
failIfEventsMatch: query,
after: lastPosition,
});
} catch (error) {
if (isAppendConditionError(error)) {
throw new Error('Username already taken');
}
throw error;
}
  • A global uniqueness constraint
  • A single event that represents the fact
  • A DCB write that rejects conflicts without sagas

If you want to go deeper, read the DCB concept doc or the uniqueness guide.