Skip to main content

Event sourcing

The hydra-node is an event sourced application. This means that the main logic is processing inputs (also called commands) and produces events. These events are saved and loaded to persist application state across restarts. Also, most events are transformed to outputs and can be observed on the hydra-node API.

On application startup, the hydrate function is called to load all events using a given EventSource and while doing so, re-emits those events to all provided EventSink instances. The resulting HydraNode will then enter the main loop of hydra-node and process inputs into state changes and effects via function stepHydraNode. All state changes of a Hydra node are based on StateEvent values and consequently get emitted to all eventSinks of the HydraNode handle. Also, the eventSource of the same may be used later to to load events on-demand, for example to produce a history of server outputs.

Head state evolution​

Hydra.HeadLogic.State.Node owns the deposit registry, Head lifecycle and observed chain time and synchronisation status. It applies state-change events to these components and assembles NodeState. Increment settlement reads the deposit's value before its registry entry is consumed. Chain time and synchronisation are updated directly in NodeState, without a separate machine.

An open Head owns CoordinatedHeadState. State.Coordinated routes ordinary transaction commands directly to Transactions; snapshot commands go to Snapshots. Snapshot changes are applied before transaction reconciliation and commit selection. These dependencies are explicit in the coordinator. The overview diagrams show ownership, while each machine's diagram shows its permitted phase transitions.

Hydra.HeadLogic.State.Types defines the shared commands and updates. The snapshot command type excludes ordinary transaction commands. Persisted state lives in Hydra.HeadLogic.State. Retained events use the same transaction and commit updates, restoring snapshot state without repeating live admission or signature verification.

Default event source and sinks​

The default event source and sink used by the hydra-node is SQLiteBased, which persists events in a SQLite database file named hydra.db. This file is located in the hydra-node persistence directory, which is specified by the --persistence-dir command line option.

A legacy state file or an incompatible database version causes startup to fail before replay. No automatic migration is available; see upgrading persistence.

As explained in the consequences of ADR29, the API server of the hydra-node is also an event sink, which means that all events are sent to the API server and may be further submitted as ServerOutput to clients of the API server. See mkTimedServerOutputFromStateEvent for which events are mapped to server outputs.

SQLite database​

Schema​

The database contains a single events table:

ColumnTypeDescription
event_idINTEGERPrimary key, matches the in-memory event id
event_dataBLOBCBOR-encoded event payload (ToCBOR/FromCBOR)

Event payloads use a constructor-name-tagged CBOR format: the constructor name as a CBOR text string, followed by the constructor fields in declaration order. This applies uniformly to every hydra domain type, including newtypes and single-constructor records (e.g. a HeadId is encoded as the text "UnsafeHeadId" followed by the raw bytes). Most instances are derived generically via genericToCBOR / genericFromCBOR from Codec.CBOR.Generic.Tagged (cborg-generic-tagged, re-exported by Hydra.Prelude), which makes the data type declaration itself the on-disk format: changing the order or types of an existing constructor's fields is a breaking change that requires a migration or fresh persistence, while adding or reordering constructors preserves the tags of existing constructors. Removing a constructor requires a compatibility decoder or migration for stored values that use it; older software cannot decode newly added constructors. The few hand-written codecs (e.g. Snapshot, Environment) carry the same leading tag and only exist where a field is deliberately omitted from the encoding. Untagged leaves are limited to standard external formats: cardano-ledger encodings for Tx/UTxO, raw-bytes/text encodings for opaque cardano-api types (TxId, PolicyId, Hash BlockHeader, ...), scalar primitives, and VerificationKey HydraKey whose CBOR is the on-disk key file format and must not change. The golden tests in Hydra.CBORSpec lock the concrete bytes per constructor and fail on any accidental format change.

The following connection pragmas are set on every open:

  • journal_mode=WAL — write-ahead logging for concurrent reads during writes
  • synchronous=NORMAL — reduces fsync frequency; recent commits may be lost after a power or operating-system failure
  • busy_timeout=5000 — wait up to 5 s for locks instead of failing immediately
  • cache_size=-65536 — 64 MB page cache
  • temp_store=MEMORY — temporary tables and indexes in memory

L1 is not a complete recovery source: signed L2 snapshots and off-chain events cannot all be reconstructed from the chain. Clean shutdowns flush pending writes; operators still need backups and reliable storage.

Async write-behind​

To keep persistence off the hot path, putEvent enqueues events in a bounded TBQueue. A background writer drains the queue, encodes the events as CBOR, and batch-inserts the rows in one transaction, amortising WAL writes across events.

The last-seen event id is updated atomically at enqueue time (not write time), so de-duplication tracking remains correct even though the physical write is deferred. Reads via sourceEvents auto-flush the write queue before reading, so callers always see all enqueued events without manual synchronisation.

Batch enqueue transactions contain at most 1,000 events, the queue capacity. Larger batches make progress as the writer drains each chunk. Deduplication is checked in the same STM transaction as enqueueing.

Startup streams replay to custom sinks in batches of at most 1,000 events. When there are no custom sinks, it skips that replay pass entirely.

Persistence compatibility​

The database schema and event format are versioned together using SQLite's PRAGMA user_version. The current version is 3, which includes the HeadLogic checkpoint layouts. Versions 1 (JSON) and 2 (earlier CBOR layouts), unversioned databases containing tables, and newer versions are rejected before replay. Their schema version and event data are left unchanged.

Only an empty, unversioned database is initialised as a new version 3 store. The events table and version are written in one transaction. A legacy state file is rejected before opening or creating hydra.db.

There is no automatic migration across this boundary. Operators must close and fan out existing Heads with the version that created their persistence, retain that directory for recovery, and use a fresh --persistence-dir for new Heads. Older releases also reject version 3 databases, preventing an accidental downgrade. See upgrading persistence.

Future changes to persisted layouts must update nextVersion in Data.EventSource.SQLite, define whether migration is supported, and test the compatibility boundary in SQLiteBasedSpec.

Examples​

Besides the default event source and sinks, the hydra-node:examples library includes a UDP event sink:

  • Hydra.Events.UDP: A simple UDP sink that sends all events to a UDP socket. This is a simple example of an event sink that can be used to send events to other applications or services.

What to test​

When implementing an event source or sink, you might want to consider testing the following, as also demonstrated by the main implementations and examples above:

  • Event store (sink + source)

    • Completeness: Any events stored by putEvent are returned by getEvents/sourceEvents
      • For continuous, non-continuous and sequences of duplicate events
    • Concurrent use of putEvent and sourceEvents is possible
  • Event sink only

    • Whether putEvent results in desired effect
    • Concurrent use of putEvent is possible
  • Event source only

    • Whether previously "primed" events are loaded by sourceEvents
    • Concurrent use of sourceEvents is possible
  • General: allocated resources are released (use with/bracket pattern)

Event Log Rotation​

Long-living heads may produce a large number of persisted events, which can impact the restart time of the hydra-node as it needs to read in all the previous to recreate its state.

Event log rotation was introduced to improve recovery times by reducing the number of events that need to be replayed on startup. This is achieved by periodically replacing the current event log with a new one that starts from a checkpoint event, which captures the latest aggregated head state.

Rotation can be enabled via the optional --persistence-rotate-after command-line argument, which specifies the number of events after which rotation should occur. When rotation triggers, the current database is first archived to a numbered file old-state/hydra-<logId>.db (a consistent snapshot taken with SQLite's VACUUM INTO, in an old-state subdirectory of the persistence directory), and only then are all events older than the checkpoint deleted from hydra.db and replaced with a single checkpoint event capturing the current aggregated state. The archive is taken before the delete, so a failure to write it aborts the rotation and leaves the events intact.

For example, with --persistence-rotate-after 100, a rotation occurs after every 100 new events. The checkpoint event captures the full node state at that point, so on the next restart the node only needs to replay events since the last checkpoint.

Note that a checkpoint event id matches the last persisted event id from the previous rotated log, preserving the sequential order of event ids across logs. This also makes it easier to identify which archived log was used to compute the checkpoint, as its event id appears in the old-state/hydra-<logId>.db file name.

Depending on the rotation configuration used, the current state file may already contain more events than the specified threshold, causing a rotation to occur immediately on startup before any new inputs are processed.

Upon rotation, a server output is produced to notify external agents when a checkpoint occurs, allowing them to perform archival or cleanup actions without interrupting the Hydra Head.

The appropriate value for --persistence-rotate-after depends on your specific use case and the expected transaction volume.

As a rough guideline, in a simple scenario (running a single party on devnet that repeatedly re-spends the same committed UTxO) we observed that setting --persistence-rotate-after 10000 results in rotated log files of about 8 MB every 3 minutes.

Keep in mind that the size and frequency of rotated files will vary depending on several factors:

  • Transaction sizes: Larger transactions result in larger event payloads.
  • Number of party members: More parties increase the number of L2 protocol messages per snapshot, generating more events.
  • Ledger UTxO size: A higher number of UTxOs increases the size of certain events like snapshots.
  • Transaction throughput (TPS): Higher TPS leads to more events being produced over time.