Skip to content

Unique username with DCB

A 15 minute tutorial for global uniqueness

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

  • 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.

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.