Skip to content

Moving Between Event Stores

The Problem

An application often starts on one event store and later needs another. A team starts on the sql store in a SQLite file, then moves to message_db on PostgreSQL.

Changing the [event_store] provider in domain.toml points the domain at an empty store. Event-sourced aggregates then load as if they were never created, and every subscription starts again from the first message.

Two parts of the old store must not be copied as they are:

  • Global positions. Each store numbers its messages across the whole store. The new store numbers the copied messages again. The copy leaves out the subscription streams, and a PostgreSQL sequence can leave gaps. The memory and message_db stores also give each snapshot row a global position. A subscription's saved position is a global position, so it has no meaning in the new store.
  • Subscription state. Each subscription keeps its read position in a position-<subscriber>-<category> stream. A subscription that failed on a message also writes failed-* and recovery-* streams. These records point at global positions in the old store.

The memory store keeps its events in the memory of one process. A separate script cannot read them, so this pattern does not move a memory store.


The Pattern

Copy the events and commands stream by stream, and rebuild the subscription positions in the new store.

  1. Keep the server running until every subscription has processed every message, and every failed message has succeeded on a retry or reached the dead letter queue.
  2. Stop every process that writes to the store: the server, the API and any worker. On a clean stop, the server writes each subscription's position.
  3. Check that protean subscriptions status shows a lag of 0 for every event-store subscription.
  4. Read the old store in global order, and write each event and command to the same stream in the new store, at the same stream position.
  5. Point every subscription at the last message in the new store.

Stream positions carry over unchanged, because each stream starts at 0 and has no gaps in every store. An aggregate's version is its stream position, so optimistic concurrency keeps working on the copied aggregates.

Once the subscriptions have caught up, they have no messages left to process in the old store. In the new store, their position is the last message, so they process only the messages written after the move.


How Protean Supports It

domain.event_store.read_all("$all") returns every message in the store in global order, page by page. It leaves out snapshot rows. A snapshot holds an aggregate's state at one version, and the repository rebuilds that state from the copied events.

Each message's metadata holds its stream name, its type and its stream position. The script writes the message back with expected_version=position - 1. The new store raises ExpectedVersionError when the stream does not already hold every earlier message, so the copy stops at the first message that would land at a different position.

The script calls _write_message on the event store. EventStore has no public method that writes a stored message as it is. The server writes each subscription's Read position message through the same method.

The new store stamps each row with the time of the copy. Each message's headers.time keeps the time of the original write. A temporal query, repository.get(id, as_of=...), reads the row time. On the new store it finds no events before the move, and it returns an aggregate's full state for any time after the move.


Applying the Pattern

The script takes two domains: source, configured with the old store, and target, configured with the new store. The script copies stored messages as they are, so neither domain needs the application's elements registered.

Check that every subscription has caught up

from typing import Any
from uuid import uuid4

from protean import Domain

# Streams that hold a subscription's own state. The script rebuilds the
# position streams in the target and leaves the others behind.
SUBSCRIPTION_STREAM_PREFIXES = ("position-", "failed-", "recovery-")


def read_positions(source: Domain) -> dict[str, dict[str, Any]]:
    """Return the last ``Read`` message of each position stream in ``source``.

    Each value holds the message's ``data`` and ``metadata``, keyed by stream
    name.

    Raises:
        RuntimeError: A subscription reads a single stream, or its stored
            position is before the last message in the stream it reads.
    """
    positions: dict[str, dict[str, Any]] = {}
    # The global position of the last event or command, by category and for $all.
    last_message: dict[str, int] = {}
    for message in source.event_store.read_all("$all"):
        stream = message.metadata.headers.stream
        if stream.startswith("position-"):
            positions[stream] = message.to_dict()
        elif not stream.startswith(SUBSCRIPTION_STREAM_PREFIXES):
            global_position = message.metadata.event_store.global_position
            last_message[source.event_store.category(stream)] = global_position
            last_message["$all"] = global_position

    for stream, last_read in positions.items():
        origin = last_read["metadata"]["domain"]["origin_stream"]
        # A single-stream subscription saves global positions but reads its
        # stream from the saved value as a stream position, so a rewritten
        # global position cannot keep its place in the target.
        if origin != "$all" and source.event_store.category(origin) != origin:
            raise RuntimeError(f"{stream} reads the single stream {origin}")
        stored = last_read["data"]["position"]
        if stored < last_message.get(origin, 0):
            raise RuntimeError(
                f"{stream} stopped at global position {stored}, before the "
                f"last message in {origin} at {last_message[origin]}"
            )
    return positions

read_positions keeps the last Read message of each position-* stream. It raises RuntimeError when a subscription's position is before the last message in the stream it reads, and the move then writes nothing. It also raises RuntimeError for a subscription to a single stream, such as bank::account-acc-1. That subscription saves the global position of each message it handles, but it reads its stream from that value as a stream position, so no rewritten global position keeps its place in the new store. A subscription with no position-* stream in the old store has no record for the script to check. In the new store it processes every copied message again.

Copy the events and commands

def copy_messages(source: Domain, target: Domain) -> None:
    """Copy every event and command from ``source`` to ``target``."""
    for message in source.event_store.read_all("$all"):
        headers = message.metadata.headers
        if headers.stream.startswith(SUBSCRIPTION_STREAM_PREFIXES):
            continue

        metadata = message.metadata.to_dict()
        # The target assigns its own positions.
        metadata.pop("event_store", None)
        target.event_store._write_message(
            headers.stream,
            headers.type,
            message.data,
            metadata,
            expected_version=message.metadata.event_store.position - 1,
        )

copy_messages skips the position-*, failed-* and recovery-* streams. The message ids in the metadata carry over, so idempotency checks and causation chains still match.

Move each subscription to the end

def move_subscriptions_to_the_end(
    target: Domain, positions: dict[str, dict[str, Any]]
) -> int:
    """Point every subscription at the last message in ``target``.

    Returns the global position the subscriptions resume after.
    """
    last = target.event_store.read_last_message("$all")
    end = last.metadata.event_store.global_position if last else 0
    for stream, last_read in positions.items():
        metadata = last_read["metadata"]
        metadata.pop("event_store", None)
        metadata["headers"]["id"] = str(uuid4())
        metadata["headers"]["time"] = target.clock.now().isoformat()
        target.event_store._write_message(stream, "Read", {"position": end}, metadata)
    return end

move_subscriptions_to_the_end writes one Read message to each position stream. The message holds the global position of the last message in the new store, and reuses the metadata of the old store's last Read message with a new id and time.

Run the move

def move_event_store(source: Domain, target: Domain) -> int:
    """Copy ``source`` into ``target`` and move the subscriptions to its end.

    Run it with every process that writes to ``source`` stopped.
    """
    # The writes run in the target's context, so a memory or sql target
    # stamps each row with the target's clock.
    with target.domain_context():
        positions = read_positions(source)
        copy_messages(source, target)
        return move_subscriptions_to_the_end(target, positions)

Run it from a one-off script or a shell. This run moves a SQLite sql store to Message DB:

# fragment
from protean import Domain

from myapp.migrate import move_event_store

source = Domain(
    name="MyApp",
    config={"event_store": {"provider": "sql", "database_uri": "sqlite:///myapp.db"}},
)
target = Domain(
    name="MyApp",
    config={
        "event_store": {
            "provider": "message_db",
            "database_uri": "postgresql://message_store@localhost:5433/message_store",
        }
    },
)
source.init(traverse=False)
target.init(traverse=False)
move_event_store(source, target)

Then change the application's [event_store] configuration to the new store and start the server.

Before you run it

  • Create the new store's tables. For the sql store, run protean db setup or apply the DDL from protean eventstore ddl. For message_db, install Message DB first.
  • Start from an empty store. A stream that already holds messages fails the copy with ExpectedVersionError.
  • Clear the dead letter queue. The script leaves failed-* streams behind. Replay or purge each message that protean eventstore dlq list shows. See protean eventstore dlq. The list shows only messages with no retries left, so step 1 waits for the retries to finish.

When a run fails partway

The messages copied before the failure stay in the new store, and a second run stops at the first of them with ExpectedVersionError. Delete every row of the new store's messages table before the next run. Message DB keeps the table in its message_store schema.

Snapshots after the move

The new store holds no snapshots. The first load of an aggregate past snapshot_threshold writes a new snapshot. To write them all at once, run protean snapshot create against the new store. See protean snapshot.


Anti-Patterns

Copying the subscription position streams

A copied position-* stream holds a global position from the old store. When the new store numbers its messages differently, the subscription skips messages or processes them twice.

Moving while the application runs

A handler or an API request that writes during the copy adds a message to the old store after the script has read past it. The new store never receives that message.

Copying a store with failed messages

A subscription that resumes in the new store has no failed-* record of the messages it could not process. Those messages stay unprocessed.


When Not to Use

  • A new application with no events yet. Change the configuration and start.
  • Moving one database's data to another database with the same store. Copy the database with its own tools, such as pg_dump. Every position stays the same, so the subscriptions need no change.

Summary

Part of the old store What the script does
Events and commands Copies them to the same stream, at the same stream position
Message ids and metadata Copies them unchanged
Row write times The new store stamps each row with the time of the copy
Snapshots Leaves them behind. The new store writes them on load, or with protean snapshot create
position-* streams Writes one new Read message at the new store's last global position
failed-* and recovery-* streams Leaves them behind. Clear the dead letter queue first