tellus
How-to guides

Evolve events

Change the shape of a stored event and let the new release read the old events by upcasting them while it replays.

Events outlive the code which wrote them. When the shape of an event changes, the events already stored keep the old shape, since tellus never rewrites the store. Instead, the new release decodes the old shape and converts it while it replays: it upcasts the old events.

The examples on this page come from a thermometer whose first release records its readings in Fahrenheit and whose second release records them in Celsius. The example holds both releases in one program. This page also assumes you know the event-sourced actors tutorial.

Version the event

tellus/examples/how_to/evolve_events.rs
#[derive(Serialize, Deserialize)]
struct RecordedV1 {
    fahrenheit: f64,
}

impl Versioned for RecordedV1 {
    const MANIFEST: &'static str = "recorded";
    const VERSION: SchemaVersion = SchemaVersion::new(1);
}

Every event implements Versioned, and tellus stores its manifest and schema version alongside the payload. The manifest is a stable name for the event type, independent of the Rust type. The schema version is that of the code which wrote the event. Release 1 stores its readings as recorded events with schema version 1.

In an application, release 1 would call this type Recorded. Release 2 keeps it under a new name, RecordedV1, only to decode the events release 1 stored.

Upcast the old version

Release 2 stores the reading in Celsius, under the same manifest and with schema version 2:

tellus/examples/how_to/evolve_events.rs
#[derive(Serialize, Deserialize)]
struct Recorded {
    celsius: f64,
}

impl Versioned for Recorded {
    const MANIFEST: &'static str = "recorded";
    const VERSION: SchemaVersion = SchemaVersion::new(2);

    fn decode<C>(
        codec: &C,
        schema_version: SchemaVersion,
        payload: &[u8],
    ) -> Result<Self, DecodeError>
    where
        C: Codec,
    {
        if schema_version == Self::VERSION {
            Ok(codec.decode(payload)?)
        } else if schema_version == RecordedV1::VERSION {
            let RecordedV1 { fahrenheit } = codec.decode(payload)?;
            Ok(Self {
                celsius: (fahrenheit - 32.0) * 5.0 / 9.0,
            })
        } else {
            Err(DecodeError::UnsupportedSchemaVersion {
                manifest: Self::MANIFEST,
                schema_version,
            })
        }
    }
}

Versioned::decode gets the codec of the Persistence, the stored schema version and the payload. The default implementation decodes the current version only. Release 2 overrides it: it decodes version 2 as it is, and version 1 as a RecordedV1, which it converts to Celsius. Every other version is an UnsupportedSchemaVersion error. tellus checks the manifest before it calls decode, so an event stored under another manifest never gets this far.

The rest of release 2 knows only Recorded. Its apply gets every event in the current shape, however old the stored one is.

What to keep in mind

An upcast stays as long as the old events. The store is never rewritten, so every full replay decodes the events of release 1 again. A recovery which starts from a snapshot replays only the events after it, but a snapshot can be discarded, and recovery then replays in full. Release 2 and every later release keep the version 1 branch for as long as a stream holds events of that version.

The manifest never changes. Once events are stored under a manifest, the type keeps it, also through a rename or a move. tellus rejects an event whose stored manifest differs from the type's MANIFEST.

Nor does the codec. Stored events do not name their codec, so the one an application starts with stays. The default is CBOR; the example selects Json with Persistence::with_codec, which makes the stored payloads readable below. Json fails to encode a NaN or an infinity.

An event which cannot be decoded fails the recovery. The actor then fails into its supervision strategy, before it handles any command. A restart fails in the same way, so the actor ends up stopped under either strategy.

The old release cannot read the new events. Release 1 decodes version 1 only, so after a rollback it fails every recovery which replays an event release 2 has appended.

Snapshots need no upcast. A snapshot which can no longer be decoded is discarded, and recovery replays the events from the start instead. The default Versioned::decode decodes the current version only. A snapshot stored under the current version is decoded as the current shape, whichever release wrote it. So raise the snapshot's schema version whenever its shape or the meaning of its values changes, such as the unit of the readings it holds. Every older snapshot is then undecodable, and hence discarded. A custom decode can still read the older ones.

Run it

tellus/examples/how_to/evolve_events.rs
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let store = InMemoryStore::default();
    let persistence = Persistence::new(store.clone()).with_codec(Json);

    let system = ActorSystem::event_sourced(ThermometerV1, persistence.clone());
    for fahrenheit in [70.7, 71.6] {
        system
            .root()
            .ask(Duration::from_secs(1), |reply_to| {
                CommandV1::Record(fahrenheit, reply_to)
            })
            .await
            .context("asking release 1 to record a reading")?;
    }
    system.stop();
    system
        .terminated()
        .await
        .context("awaiting the termination of release 1")?;
    print_stored_events(&store);

    let system = ActorSystem::event_sourced(Thermometer, persistence);
    system.root().tell(Command::Record(22.4));
    let readings = system
        .root()
        .ask(Duration::from_secs(1), Command::Read)
        .await
        .context("asking release 2 for the readings")?;
    let readings = readings
        .iter()
        .map(|celsius| format!("{celsius:.1}"))
        .collect::<Vec<_>>()
        .join(", ");
    println!("Readings in Celsius: {readings}");
    system.stop();
    system
        .terminated()
        .await
        .context("awaiting the termination of release 2")?;
    print_stored_events(&store);

    Ok(())
}

Release 1 records two readings and stops. Release 2 recovers from the same store, records a third reading and is asked for all of them. It was told the reading before it was asked, so the answer includes it. From a clone of the tellus repository:

cargo run --quiet -p tellus --features persistence-in-memory --example how_to_evolve_events
Stored event 0: recorded version 1, {"fahrenheit":70.7}
Stored event 1: recorded version 1, {"fahrenheit":71.6}
Readings in Celsius: 21.5, 22.0, 22.4
Stored event 0: recorded version 1, {"fahrenheit":70.7}
Stored event 1: recorded version 1, {"fahrenheit":71.6}
Stored event 2: recorded version 2, {"celsius":22.4}

Release 2 answers all three readings in Celsius: the first two are the Fahrenheit readings of release 1, upcast during its recovery. Afterward the store holds both versions side by side, and the events of release 1 are still the ones release 1 wrote.