ActaDB

Every Email Address Only Once

The uniqueness of email addresses is a very common example, and it is small enough to fit into one file. An address can be registered only once. The program does this in two ways, and it prints what each request read and how long it took.

Run It

The whole program is one file. You run it from the root of the repository.

git clone https://github.com/ricofritzsche/actadb
cd actadb
cargo run --release -p unique-email

Every registered address is one EmailRegistered event, and its payload is the address.

fn registered(email: &str) -> Event {
    Event {
        event_type: EMAIL_REGISTERED.to_string(),
        payload: email.as_bytes().to_vec(),
    }
}

Way One: Read Everything

Every request reads all EmailRegistered events, checks whether the address is among them, and appends with the token of its read.

fn register_with_full_read(
    store: &EventStore,
    email: &str,
) -> Result<(Registration, usize), StoreError> {
    let mut records_read = 0;
    for _attempt in 1..=3 {
        let selection = store.query(&Query::event_types([EMAIL_REGISTERED]))?;
        records_read += selection.records.len();
        let taken = selection
            .records
            .iter()
            .any(|record| record.payload == email.as_bytes());
        if taken {
            return Ok((Registration::Taken, records_read));
        }
        match store.append(vec![registered(email)], Some(selection.token))? {
            Commit::Appended { .. } => return Ok((Registration::Registered, records_read)),
            Commit::Conflict => continue,
        }
    }
    Ok((Registration::NotProcessed, records_read))
}

This is all the code the rule needs. Its cost is the read, because a request reads every registered address every time.

Way Two: Keep What You Read

The program keeps the addresses it has read, together with the checkpoint of its last read. Only the first request reads all EmailRegistered events. Every later request reads what was stored after the checkpoint and adds it to the kept addresses.

struct KnownEmails {
    emails: BTreeSet<Vec<u8>>,
    checkpoint: Option<Checkpoint>,
}

fn register_with_kept_emails(
    store: &EventStore,
    known: &mut KnownEmails,
    email: &str,
) -> Result<(Registration, usize), StoreError> {
    let mut records_read = 0;
    for _attempt in 1..=3 {
        let selection = match &known.checkpoint {
            None => store.query(&Query::event_types([EMAIL_REGISTERED]))?,
            Some(checkpoint) => store.query_after(checkpoint)?,
        };
        records_read += selection.records.len();
        for record in selection.records {
            known.emails.insert(record.payload);
        }
        known.checkpoint = Some(selection.checkpoint);
        if known.emails.contains(email.as_bytes()) {
            return Ok((Registration::Taken, records_read));
        }
        match store.append(vec![registered(email)], Some(selection.token))? {
            Commit::Appended { .. } => return Ok((Registration::Registered, records_read)),
            Commit::Conflict => continue,
        }
    }
    Ok((Registration::NotProcessed, records_read))
}

Notice that the append is the same as in way one. Only the read changed.

What It Prints

The program first stores 100,000 registered addresses. This is the output on my machine.

100000 email addresses are registered.

Way 1, full read: every request reads all registered addresses.
  ada@example.com    Registered   records read: 100000   time:  44.39 ms
  ada@example.com    Taken        records read: 100001   time:  36.70 ms
  bob@example.com    Registered   records read: 100001   time:  46.49 ms

Way 2, kept addresses: only the first request reads all registered addresses.
  cleo@example.com   Registered   records read: 100002   time:  52.18 ms
  cleo@example.com   Taken        records read:      1   time:   0.01 ms
  dan@example.com    Registered   records read:      0   time:   6.13 ms

The condition: an append is refused when an address was registered after the read.
  eve@example.com    Conflict
  eve@example.com    Taken        records read:      2   time:   0.01 ms

In way one every request reads about 100,000 records and takes around 40 ms. In way two the second request reads one record, the one that the first request appended itself, and it answers in a fraction of a millisecond. The request for dan@example.com reads nothing and still takes 6 ms. That is the time of the append.

The last part shows the condition. A request reads, then eve@example.com is registered by another request, and then the first request appends with the token of its read. The store answers with a conflict and stores nothing.

The page Insights puts both ways side by side.

A Whole Application

The email example shows how you use the store. It does not show how several commands work on the same events. For this I added a second example to the repository, a warehouse app with five commands, two queries and an HTTP API. You receive goods, reserve them for an order, issue them and count stock.

Its README takes you through a first round and shows how the app is built.