Event Store Internals

This chapter covers the specifics of working with an Event Store in Axon Framework. Most of these components work without user interaction. The exception is append criteria per command, which are declared next to command handlers.

The page covers:

  • Dynamic Consistency Boundaries (DCB), a flexible approach to organizing events beyond traditional aggregate-based storage.

  • Event tags and the TagResolver for attaching metadata to events, and EventCriteria and the CriteriaResolver for querying events based on those tags.

  • Append criteria per command, which check a different consistency boundary for a command than the one it sourced, including for entity command handlers.

  • Append, source, and stream conditions, and the consistency markers that detect conflicting writes.

Dynamic Consistency Boundary

The Dynamic Consistency Boundary, or DCB for short, allows for a flexible boundary to what should be appended consistently with other existing event streams in the event store. In other words, DCB provides a flexible approach to organizing and querying events. In doing so, it eliminates the focus on the aggregate identifier, replacing it for user defined tags. Note that tags are plural. As such, an event is no longer either attached to zero or one aggregate/entity, but potentially several due to DCB.

This shift provides great flexibility in deriving models, as there is no longer a hard boundary around, for example, an aggregate stream. It allows users to depend on N-"aggregate" streams in one sourcing operation, allowing commands to span a complete view of the task at hand.

To not overencumber the sourcing operation of an EventStore, not only tags, but also (event) "types" are used when reading events. The types act as a filter on the entity streams that matches the tags. The tags and the types combined from the event criteria. It is this EventCriteria that Axon Framework uses for appending events, sourcing events to recreate entities, and streaming events.

You could conclude that DCB makes the base event store operations of appending, sourcing, and streaming focus on an 0-N event stream focus instead of 0-or-1 event stream.

Tags

Aligning with the dynamic consistency boundary means that an event has zero to N tags. Axon has the Tag class for this, which typically:

  • Represent a (domain/business specific) identifier.

  • Represent an event type.

You are only ever required to directly construct a Tag in Axon if you are constructing an EventCriteria from scratch. The event criteria section provides more details on this.

In most cases, the TagResolver will take the task of resolving the Tags for an event. The TagResolver inspects events and derives tags based on annotations or custom logic, reducing boilerplate and ensuring consistent tagging across your application.

Axon provides the @EventTag annotation for tag definition on event classes:

import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.messaging.eventhandling.annotation.Event;

@Event(name = "orderPlaced")
record OrderPlacedEvent(
    @EventTag OrderId customerId,
    @EventTag(key = "region") String orderRegion,
    String orderId
) {
}

When an OrderPlacedEvent is appended, the TagResolver automatically extracts customerId and region as tags from the annotated fields. By default, the tag key matches the field name, but you can override it by specifying a value in the annotation (as shown with "region").

For more complex scenarios, you can implement a custom TagResolver:

import org.axonframework.eventsourcing.eventstore.TagResolver;
import org.axonframework.messaging.eventhandling.EventMessage;
import org.axonframework.messaging.eventstreaming.Tag;

import java.util.Set;

public class CustomTagResolver implements TagResolver {

    @Override
    public Set<Tag> resolve(EventMessage event) {
        Object payload = event.payload();
        if (payload instanceof OrderPlacedEvent orderEvent) {
            return Set.of(
                    Tag.of("orderId", orderEvent.orderId().toString())
            );
        }
        // You will require an if for every event (set)!
        return Set.of();
    }
}

This example shows use of the Tag#of(String, String) operation, clarifying Axon expects the tag key and value to resolve to a workable String. Note that this will require you to write an if-block for every type of or set of events to be able to deduce an actual tag.

Event criteria

Where tags form the basis for an event query, these tags need to be combined in the right order to come to an actual criteria. This is the job of the event criteria, or EventCriteria, in Axon. The EventCriteria will be used in specific conditions when querying events. Here’s an example of an event criteria with a identifier tag and type tag:

import org.axonframework.messaging.eventstreaming.EventCriteria;
import org.axonframework.messaging.eventstreaming.Tag;

public EventCriteria createCriteriaFor(OrderPlacedEvent event) {
    return EventCriteria.havingTags(Tag.of("orderId", event.orderId().toString()))
                        .andBeingOneOfTypes("OrderPlaced");
}

It is the EventCriteria that allows you to define "slices" of an otherwise potentially large entity. Events that (although part of the entity’s stream) don’t influence the decision-making, can be omitted when sourcing an entity.

In most cases, Axon can construct an EventCriteria for you automatically:

  • Appending - When appending, we combine the condition used for sourcing with the outcome of invoking the tag resolver with newly appended events.

  • Sourcing - When sourcing a single entity stream we use the entity’s identifier.

  • Streaming - When streaming we combine the names of all subscribed event handlers into a criteria.

There are two scenarios remaining where you would be required to construct an EventCriteria yourself.

If you want to event source an entity based on several streams, you need to define a CriteriaResolver yourself, as we (currently) cannot deduce the correct EventCriteria to construct for this.

When using an autodetected entity, you can add an @EventCriteriaBuilder annotated method to your event sourced entity:

import org.axonframework.eventsourcing.annotation.EventCriteriaBuilder;
import org.axonframework.eventsourcing.annotation.EventSourcedEntity;
import org.axonframework.messaging.eventstreaming.EventCriteria;
import org.axonframework.messaging.eventstreaming.Tag;

@EventSourcedEntity
public class StudentSubscribedToCourseState {

    @EventCriteriaBuilder
    private static EventCriteria resolveCriteria(SubscriptionId id) {
        String courseId = id.courseId().toString();
        String studentId = id.studentId().toString();
        return EventCriteria.either(
                EventCriteria
                        .havingTags(Tag.of("courseID", courseId))
                        .andBeingOneOfTypes(
                                CourseCreated.class.getName(),
                                CourseCapacityChanged.class.getName(),
                                StudentSubscribedToCourse.class.getName(),
                                StudentUnsubscribedFromCourse.class.getName()
                        ),
                EventCriteria
                        .havingTags(Tag.of("studentId", studentId))
                        .andBeingOneOfTypes(
                                StudentEnrolledInFaculty.class.getName(),
                                StudentSubscribedToCourse.class.getName(),
                                StudentUnsubscribedFromCourse.class.getName()
                        )
        );
    }

    // Entity fields and event sourcing handlers omitted...
}

When an StudentSubscribedToCourseState entity is loaded, the CriteriaResolver automatically calls the @EventCriteriaBuilder method to determine which events to source. The method must be static and return an EventCriteria. If no @EventCriteriaBuilder method is defined, the resolver falls back to the tagKey attribute of @EventSourcedEntity, or uses the entity’s simple class name as the tag key.

For more complex scenarios or when taking a declarative configuration approach, you can implement a custom CriteriaResolver:

import org.axonframework.eventsourcing.CriteriaResolver;
import org.axonframework.messaging.core.unitofwork.ProcessingContext;
import org.axonframework.messaging.eventstreaming.EventCriteria;
import org.axonframework.messaging.eventstreaming.Tag;

public class CustomCriteriaResolver implements CriteriaResolver<SubscriptionId> {

    @Override
    public EventCriteria resolve(SubscriptionId id, ProcessingContext context) {
        String courseId = id.courseId().toString();
        String studentId = id.studentId().toString();
        return EventCriteria.either(
                EventCriteria
                        .havingTags(Tag.of("courseID", courseId))
                        .andBeingOneOfTypes(
                                CourseCreated.class.getName(),
                                CourseCapacityChanged.class.getName(),
                                StudentSubscribedToCourse.class.getName(),
                                StudentUnsubscribedFromCourse.class.getName()
                        ),
                EventCriteria
                        .havingTags(Tag.of("studentId", studentId))
                        .andBeingOneOfTypes(
                                StudentEnrolledInFaculty.class.getName(),
                                StudentSubscribedToCourse.class.getName(),
                                StudentUnsubscribedFromCourse.class.getName()
                        )
        );
    }
}

Append criteria per command

Sourcing criteria select the events that rebuild state. Append criteria select the concurrent events that conflict with a command’s decision. By default, the append criteria of a command are its complete sourcing criteria: the OR-union of everything it sourced.

A command can narrow or replace that boundary when possible and/or necessary. A narrower boundary avoids conflicts, and retries, on concurrent events the decision does not depend on.

Declaring append criteria

Declare an @AppendCriteriaBuilder on the command-handling class, for the commands whose boundary differs:

import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.commandhandling.annotation.AppendCriteriaBuilder;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.core.QualifiedName;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
import org.axonframework.messaging.eventstreaming.EventCriteria;
import org.axonframework.modelling.annotation.InjectEntity;

public class CreditCommandHandler {

    @CommandHandler
    void handle(UseCredits command,
                @InjectEntity(idProperty = "accountId") CreditBalance balance,
                EventAppender eventAppender) {
        if (balance.amount() < command.amount()) {
            throw new IllegalStateException("Insufficient credits");
        }
        eventAppender.append(new CreditsUsed(command.accountId(), command.amount()));
    }

    @CommandHandler
    void handle(TopUpCredits command,
                @InjectEntity(idProperty = "accountId") CreditBalance balance,
                EventAppender eventAppender) {
        eventAppender.append(new CreditsToppedUp(command.accountId(), command.amount()));
    }

    // a concurrent top-up only raises the balance, so only a concurrent CreditsUsed can invalidate this decision;
    // TopUpCredits has no builder and keeps its sourcing criteria
    @AppendCriteriaBuilder
    static EventCriteria appendCriteria(UseCredits command, EventCriteria sourcingCriteria) {
        return sourcingCriteria.withEventTypes(new QualifiedName(CreditsUsed.class));
    }
}

The builder receives the command and the accumulated sourcing criteria, and returns the complete append criteria for that command. When the command loads several entities, the supplied criteria are the union of all of them. withEventTypes keeps the tags of every OR branch and replaces its event types, so a builder narrows the boundary without repeating the sourcing tags. Event types are QualifiedName or String names, and new QualifiedName(SomeEvent.class) gives the default name of an event class. For events named with @Event, or with a custom MessageTypeResolver, use withEventTypes(MessageTypeResolver, Class<?>…​).

An event-sourced entity that handles commands declares append criteria the same way, next to its @EventCriteriaBuilder:

import org.axonframework.eventsourcing.annotation.EventCriteriaBuilder;
import org.axonframework.eventsourcing.annotation.EventSourcedEntity;
import org.axonframework.eventsourcing.annotation.EventSourcingHandler;
import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.commandhandling.annotation.AppendCriteriaBuilder;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.core.QualifiedName;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
import org.axonframework.messaging.eventstreaming.EventCriteria;
import org.axonframework.messaging.eventstreaming.Tag;
import org.axonframework.modelling.entity.annotation.EntityMember;

import java.util.ArrayList;
import java.util.List;

@EventSourcedEntity(tagKey = "accountId")
public class Account {

    private int balance = 0;

    @EntityMember(routingKey = "cardId")
    private final List<Card> cards = new ArrayList<>();

    // Sourcing: every event type needed to rebuild the state a decision reads.
    @EventCriteriaBuilder
    static EventCriteria sourcingCriteria(String accountId) {
        return EventCriteria.havingTags(Tag.of("accountId", accountId))
                            .andBeingOneOfTypes(new QualifiedName(MoneyDeposited.class),
                                                new QualifiedName(MoneyWithdrawn.class),
                                                new QualifiedName(CardIssued.class),
                                                new QualifiedName(CardReplaced.class));
    }

    @EventSourcingHandler
    void evolve(MoneyDeposited event) {
        balance += event.amount();
    }

    @EventSourcingHandler
    void evolve(MoneyWithdrawn event) {
        balance -= event.amount();
    }

    @EventSourcingHandler
    void evolve(CardIssued event) {
        cards.add(new Card(event.cardId()));
    }

    @CommandHandler
    void handle(WithdrawMoney command, EventAppender eventAppender) {
        if (balance < command.amount()) {
            throw new IllegalStateException("Insufficient balance");
        }
        eventAppender.append(new MoneyWithdrawn(command.accountId(), command.amount()));
    }

    // Appending: only the events that can invalidate the decision above. A concurrent withdrawal can
    // overdraw the account, a concurrent deposit only ever raises the balance, so deposits are left out.
    @AppendCriteriaBuilder
    static EventCriteria appendCriteria(WithdrawMoney command, EventCriteria sourcingCriteria) {
        return sourcingCriteria.withEventTypes(new QualifiedName(MoneyWithdrawn.class));
    }

    static class Card {

        private final String cardId;
        private int replacements = 0;

        Card(String cardId) {
            this.cardId = cardId;
        }

        @EventSourcingHandler
        void evolve(CardReplaced event) {
            replacements++;
        }

        @CommandHandler
        void handle(ReplaceCard command, EventAppender eventAppender) {
            eventAppender.append(new CardReplaced(command.accountId(), command.cardId()));
        }

        @AppendCriteriaBuilder
        static EventCriteria appendCriteria(ReplaceCard command, EventCriteria sourcingCriteria) {
            return sourcingCriteria.withEventTypes(new QualifiedName(CardReplaced.class));
        }
    }
}

@EventCriteriaBuilder selects the events the entity reads, and @AppendCriteriaBuilder selects the events a command handled by the entity conflicts with. Above, a withdrawal reads deposits, but a concurrent deposit cannot overdraw the account, so deposits are not part of the boundary. Builders on an entity apply to the commands that entity handles, including commands creating it, not to every use of the entity. Both builders are optional: without an @EventCriteriaBuilder the entity is sourced by its tag, and without an @AppendCriteriaBuilder a command keeps its sourcing criteria.

The @AppendCriteriaBuilder is internally structured as a @CommandHandlerInterceptor, so it is found and matched like any command handler interceptor.

There are a couple of rules when it comes to the append criteria builder:

  • A builder applies to the commands handled on its class whose payload is assignable to its first parameter. A first parameter of type CommandMessage applies to every command. The payload is converted to the handler’s type first, so a builder also matches serialized commands and commands named with @Command(name = …​).

  • Commands without a matching builder keep their sourcing criteria.

  • At most one builder applies to a command. When two builders, or a builder and an AppendCriteriaInterceptor, match the same command, the application still starts, but handling that command fails.

  • A nested entity declares builders for its own handlers, as Card does above. Builders of the parent entity also see the commands forwarded to its children, so keep them to the parent’s own command types.

  • A builder is static and returns EventCriteria, or startup fails with an AxonConfigurationException.

  • An EventCriteria parameter receives the sourcing criteria. Other parameters are resolved when the events are appended, so they must resolve without waiting. Only an allow-list is accepted, checked at startup: CommandMessage or Message, Metadata, a @MetadataValue, ProcessingContext, the MessageTypeResolver, and a configured component through @InjectComponent. Any other parameter, such as an unannotated component, an entity or an EventAppender, fails at startup.

Declarative configuration

Without annotations, register an AppendCriteriaInterceptor on the command-handling module:

import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.commandhandling.AppendCriteriaInterceptor;
import org.axonframework.eventsourcing.configuration.EventSourcingConfigurer;
import org.axonframework.messaging.commandhandling.SimpleCommandHandlingComponent;
import org.axonframework.messaging.commandhandling.configuration.CommandHandlingModule;
import org.axonframework.messaging.core.MessageStream;
import org.axonframework.messaging.core.QualifiedName;

public class CreditCommandConfiguration {

    public static EventSourcingConfigurer configure(EventSourcingConfigurer configurer) {
        return configurer.registerCommandHandlingModule(
                CommandHandlingModule.named("credit-commands")
                                     .commandHandlers()
                                     .commandHandlingComponent(
                                             configuration -> SimpleCommandHandlingComponent
                                                     .create("credit-command-handler")
                                                     .subscribe(new QualifiedName("credits.UseCredits"),
                                                                (command, context) -> MessageStream.empty())
                                                     .subscribe(new QualifiedName("credits.TopUpCredits"),
                                                                (command, context) -> MessageStream.empty())
                                     )
                                     .intercepted(configuration -> AppendCriteriaInterceptor
                                             .forCommand(new QualifiedName("credits.UseCredits"),
                                                         sourcingCriteria -> sourcingCriteria.withEventTypes(
                                                                 new QualifiedName(CreditsUsed.class)
                                                         ))
                                     )
        );
    }
}

forCommand and andForCommand register criteria per command name, the way SimpleCommandHandlingComponent subscribes handlers. Commands are matched by name, so the payload is not converted, and commands without registered criteria keep their sourcing criteria, here credits.TopUpCredits. Registering the same name twice fails right away with an AxonConfigurationException. The interceptor is immutable: andForCommand returns a new interceptor, so register everything before handing it to the module. Pass an AppendCriteriaResolver instead of a function when the criteria depend on the command or the context.

To decide for every command of every component in the module, use AppendCriteriaInterceptor.forAllCommands(fallback) with one AppendCriteriaResolver. That resolver receives the command as dispatched, so read a serialized payload with payloadAs. Criteria added with andForCommand take precedence over it for their command. A command whose criteria more than one resolver decides, for example a builder and an interceptor, fails when it is handled; startup does not detect this.

For a declaratively built entity, register the interceptor on the metamodel builder through EntityCommandHandlerInterceptor.of:

import org.axonframework.common.configuration.Configuration;
import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.commandhandling.AppendCriteriaInterceptor;
import org.axonframework.messaging.core.MessageStream;
import org.axonframework.messaging.core.QualifiedName;
import org.axonframework.modelling.entity.EntityCommandHandlerInterceptor;
import org.axonframework.modelling.entity.EntityMetamodel;
import org.axonframework.modelling.entity.EntityMetamodelBuilder;

public class DeclarativeEntityAppendCriteria {

    // Used as EventSourcedEntityModule.declarative(String.class, CreditBalance.class)
    //                                 .messagingModel(DeclarativeEntityAppendCriteria::messagingModel)
    public static EntityMetamodel<CreditBalance> messagingModel(Configuration configuration,
                                                                EntityMetamodelBuilder<CreditBalance> builder) {
        AppendCriteriaInterceptor appendCriteria = AppendCriteriaInterceptor
                .forCommand(new QualifiedName("credits.UseCredits"),
                            sourcingCriteria -> sourcingCriteria.withEventTypes(new QualifiedName(CreditsUsed.class)));
        return builder
                .instanceCommandHandler(new QualifiedName("credits.UseCredits"),
                                        (command, balance, context) -> MessageStream.empty().cast())
                .instanceCommandHandler(new QualifiedName("credits.TopUpCredits"),
                                        (command, balance, context) -> MessageStream.empty().cast())
                .commandHandlerInterceptor(EntityCommandHandlerInterceptor.of(appendCriteria))
                .build();
    }
}

The interceptor covers the creational and instance commands of the entity, and the commands forwarded to its child entities. On a polymorphic entity, register it once on the polymorphic metamodel, which also covers the commands of its concrete types.

Commands without sourcing

A command that sources nothing and declares no append criteria appends unconditionally. A builder for such a command can return criteria built from the command or its metadata. The event store checks them against the complete history, which reserves a unique key without loading anything:

import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.commandhandling.annotation.AppendCriteriaBuilder;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.core.annotation.MetadataValue;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
import org.axonframework.messaging.eventstreaming.EventCriteria;

public class UsernameCommandHandler {

    @CommandHandler
    void handle(RegisterUsername command,
                @MetadataValue(value = "tenantId", required = true) String tenantId,
                EventAppender eventAppender) {
        eventAppender.append(new UsernameRegistered(tenantId, command.username()));
    }

    @AppendCriteriaBuilder
    static EventCriteria appendCriteria(
            RegisterUsername command,
            @MetadataValue(value = "tenantId", required = true) String tenantId
    ) {
        return EventCriteria.havingTags(
                "tenantId", tenantId,
                "username", command.username()
        );
    }
}
  • The append fails if a matching event already exists or is appended concurrently.

  • Tag the appended events with the values the criteria use, as the example does with tenantId.

  • Returning the supplied criteria keeps the command unconditional.

  • An entity created without loading is the exception. Its builder receives criteria that select all tags of the appended events, and the event store checks them from the start of the history. An event matches only if it has all of those tags, so this check rejects only an exact repeat.

  • Setting event types with withEventTypes on the supplied criteria defines a boundary where there was none, so every event of those types in the history is checked. A CommandMessage builder that does this applies it to every command that sources nothing.

  • A command that sourced something checks its append criteria only after the position it read, whatever the criteria select. To check a key from the beginning of the history, use a command that sources nothing.

To keep an entity unique by its identifier and by another value, return criteria for each tag and join them with or:

import org.axonframework.eventsourcing.annotation.EventSourcedEntity;
import org.axonframework.eventsourcing.annotation.EventTag;
import org.axonframework.eventsourcing.annotation.reflection.EntityCreator;
import org.axonframework.eventsourcing.commandhandling.annotation.AppendCriteriaBuilder;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
import org.axonframework.messaging.eventstreaming.EventCriteria;

@EventSourcedEntity(tagKey = "userId")
public class User {

    @EntityCreator
    User() {
    }

    @CommandHandler
    static void handle(RegisterUser command, EventAppender eventAppender) {
        eventAppender.append(new UserRegistered(command.userId(), command.username()));
    }

    // Fails the command if any event in the history has this user id or this username.
    @AppendCriteriaBuilder
    static EventCriteria appendCriteria(RegisterUser command) {
        return EventCriteria.havingTags("userId", command.userId())
                            .or(EventCriteria.havingTags("username", command.username()));
    }
}

// Without @TargetEntityId the framework creates the entity without loading it,
// so the event store checks the append criteria from the start of the history.
record RegisterUser(String userId, String username) {
}

record UserRegistered(@EventTag(key = "userId") String userId, @EventTag(key = "username") String username) {
}

RegisterUser has no @TargetEntityId, so the framework creates the User without loading it. The event store checks the criteria from the start of the history and rejects a second user with the same identifier or the same username. Without the builder, a second RegisterUser with the same identifier and another username succeeds, because its event has different tags.

With @TargetEntityId on RegisterUser, the framework loads the User first. The framework then rejects a second registration with the same identifier. The event store checks the username only against events appended after that read, so it does not detect an earlier user with the same username.

Choosing a narrower boundary

A narrower boundary can change how stored events explain a decision: a rejection may describe the state before a concurrent event that the boundary excluded. Keep the default boundary when that order matters more than avoiding retries, for example for audit records.

A builder is a static method, so its result can be tested without running a command. Assert with criteria.matches(eventType, tags) that it selects the events the decision depends on, as an event type name that matches nothing silently selects nothing.

Aggregate-based storage

Aggregate-based storage detects conflicts only through the sequence numbers of the aggregates it appends to. It does not check append criteria, so an append criteria builder has no effect there. A command that sourced an aggregate still conflicts with any concurrent event of that aggregate, whatever its builder returns. A command that sourced nothing only conflicts when it creates an aggregate that already exists. Reserving a unique key, as in the UsernameCommandHandler example, requires a criteria-aware event store.

Append, source, and stream conditions

While event criteria define what events to match, conditions wrap this criteria with additional context for specific event store operations. Axon provides three condition types, each tailored for a different operation:

AppendCondition

Used when appending events to the event store. It combines an EventCriteria with a ConsistencyMarker to enforce write conflict detection. The consistency marker tracks the position until which the criteria should be validated. If events matching the criteria were appended after this position, the append operation fails. This ensures that concurrent writes to the same logical boundary are detected.

For events that don’t participate in any consistency boundary (such as standalone events), use AppendCondition.none().

SourcingCondition

Used when sourcing events to rebuild entity state. It combines an EventCriteria with a starting Position in the event sequence. The criteria determines which events to retrieve, while the position allows sourcing from a specific point (useful when loading from a snapshot).

This condition is what the CriteriaResolver ultimately produces when loading an event-sourced entity.

StreamingCondition

Used when streaming events for event processors. It combines an EventCriteria with a TrackingToken that marks the position to start streaming from. Unlike sourcing (which retrieves a bounded sequence), streaming is continuous and open-ended.

The criteria defaults to matching any tag, making it suitable for processors that need to observe all events rather than a specific entity stream.

In practice, most users won’t construct these conditions directly, as you do not have to interact with the EventStore directly. Axon builds the appropriate condition based on the operation:

  • When appending, the framework combines the sourcing condition with tags from newly appended events.

  • When sourcing, the CriteriaResolver constructs the condition from the entity identifier.

  • When streaming, event processors construct the condition from their subscribed event handler names.

Consistency marker

To support a dynamic consistency boundary with an event store, a consistency marker is a hard requirement. The consistency marker is returned as the final entry when sourcing events from an event store. As such, it tracks the logical grouping of sourced events.

When appending events with tags, thus as part of a sourced entity, Axon automatically attaches this consistency marker to the append condition. In doing so, we prevent write conflicts, ensuring that concurrent writes to the same logical boundary are detected and handled appropriately.

As with many components in this chapter, the chance is slim you will need to interact with the ConsistencyMarker directly. However, being aware of the internals could just be what you are searching for.