Rivaskel Academy
Rivaskel Academy

Data contracts and event schemas

Data modelling

Define the agreement before choosing a format

An event contract says what a producer asserts and what a consumer can safely infer. A JSON or Avro schema can constrain property names and types, but a working contract also describes identity, time, units, validity and correction. Fields are useful only when their semantics survive replay and when two teams interpret them the same way.

Consider a shop that publishes a PaymentCaptured event after settlement. “Amount is a number” leaves the ledger team to guess the currency, decimal precision and handling of partial captures. “A non-negative integer number of minor units for currency, belonging to exactly this capture operation” sets a testable boundary. The contract still needs to say whether a partial capture is a new event, how reversals appear and who verifies currency-specific decimal conventions.

Envelopes, payloads and physical delivery

A small event envelope is valuable when dozens of producers share a transport. Typical envelope fields include an event identifier, event type, schema version, subject identifier, producer and event time. The payload represents the business decision. Delivery systems may enrich the record with ingestion time, topic, partition, offset or file path. Preserve that provenance separately from the facts the producer controlled.

This example describes a partial capture. The transport might deliver it more than once, but the original identity remains unchanged across deliveries.

{
  "event_id": "cap-94e3",
  "event_type": "PaymentCaptured",
  "schema_version": 1,
  "subject_id": "order-802",
  "occurred_at": "2026-03-19T15:22:05Z",
  "producer": "payments-core",
  "payload": {
    "payment_id": "pay-174",
    "currency": "GBP",
    "amount_minor": 1250,
    "is_final_capture": false
  }
}

An accepted row with amount_minor=0 can mean genuinely zero if the contract allows it. Missing amount can mean an invalid event, while null might only mean explicitly unknown if the schema allows nullable amounts. A consumer that silently converts all three to zero will produce a table that is easy to load and difficult to trust. Keep those conditions explicit.

For financial measurements, use integer minor units or a fixed-precision decimal with a documented scale. Avoid floating-point accumulation for exact balances. When a warehouse aggregates multiple currencies, group by currency unless a governed exchange-rate step has converted to a common reporting currency.

Version changes and compatibility

Compatibility has direction. A new consumer needs to read records that old producers already emitted, especially when it replays a durable topic or landing zone. An older consumer might need to coexist with a new producer during a rolling release. The combination dictates which changes are safe. Compatibility rules depend on the serialization technology and registry configuration. Treat a generic compatibility label as a statement to test against actual readers, writers and retained history.

Adding a field with a meaningful default often looks compatible, but old consumers can still reject unknown properties if they enforce a closed schema. A change from integer to string can silently break a query even if the transport accepts it. Changing a field's meaning while retaining its name and type is especially dangerous. For example, changing occurred_at from capture time to publish time would move legitimate events between reporting windows with no JSON validation error.

Decide whether successive versions represent one concept with a compatible shape or a different business event. A new type such as PaymentReversed may express intent more clearly than a negative number under PaymentCaptured. If a producer sends both old and new representations during a migration, label or route them so the sink does not count them as separate meaningful events.

Design the bad-record path

A contract is useful only when its failures can be managed. Categorize an invalid message before deciding what to do. A missing required identifier can go to quarantine under a referenced raw record ID. A transient lookup timeout can be retried under bounded policy. A suspected semantic inconsistency, such as a late event with a valid shape and a conflicting sequence, may need its own review queue. These failures require different owners.

Give a quarantine record enough metadata for triage: ingress time, producer, version, original record reference, validation rule and a compact error code. Avoid copying unnecessary sensitive values into error logs. Retain the immutable raw evidence within established policy so a fixed validator can reprocess it with the original identity and time. A dead-letter queue without an owner and replay protocol is a place to lose data more slowly.

Lab: make assumptions testable

A producer emits these records in order of delivery:

ID Version Event time Currency Amount Interpretation
cap-1 1 15:10Z GBP 800 First partial capture
cap-1 1 15:10Z GBP 800 Duplicate delivery
cap-2 1 15:12Z GBP 500 Another capture
cap-3 1 15:09Z NULL 400 Missing required currency
cap-4 2 15:15Z GBP 600 Has new optional terminal ID

Write acceptance rules for event identity, currency and time. Identify which records belong in the fact table and which should be quarantined. State how an older consumer is meant to behave if it reads version 2. Add one contract test that would catch a bad timestamp even when its value is syntactically valid.

Worked reasoning

Three independent capture IDs with amounts 800, 500 and 600 respectively produce 1,900 GBP minor units if version 2 is compatible with the intended consumer. Deduplicate cap-1 by stable ID, not by subject, price or delivery time. Quarantine cap-3 and record the missing-currency reason without interpreting it as zero. Check event time semantics through an integration fixture that exercises a delayed publisher and verifies that the field stays fixed after the delay.

A practical conformance test builds representative records from the producer artifact, reads them using current and previous consumer builds where coexistence is required, and checks outputs and quarantine behavior. Include fixtures for nullability, old data, late delivery, duplicate delivery and the smallest valid canonical representation.

Validate a payload, a record identity and a delivery separately

A digital lending service receives a catalog event whenever a partner makes a book unavailable in a region. The producers agree on JSON and an event type, but there are three distinct contracts. The payload contract says what values and representation are valid. The business event contract says when two representations describe the same change. The delivery contract says how receivers handle repeated, delayed or out-of-order submissions. Combining all three into an informal schema comment leaves ambiguous behaviour during a producer rollout.

The following partial JSON Schema illustrates payload boundaries. A contract also needs versioning, an ownership record, and examples with documented semantics.

{
  "type": "object",
  "required": ["event_id", "title_id", "region", "effective_at", "available"],
  "properties": {
    "event_id": {"type": "string", "minLength": 1},
    "title_id": {"type": "string", "minLength": 1},
    "region": {"type": "string", "enum": ["UK", "IE", "DE"]},
    "effective_at": {"type": "string", "format": "date-time"},
    "available": {"type": "boolean"}
  }
}

Shape checks alone do not ensure that the referenced title exists, that the region is permitted for the producer, or that timestamp semantics match the product's agreement. Whether the validator enforces the format keyword depends on its dialect and configuration. Configure and test it explicitly. A date-time value denotes an instant with an explicit offset, while business might require a named local time zone for calculating a date boundary. Preserve the original value or source zone when later reinterpretation depends on it. If title availability must be changed only by the responsible provider, authenticate identity independently of a self-reported producer property.

Define equivalence before deduplicating

Suppose event ID north:7721 arrives three times. The first and second have identical content but differ in broker receipt ID. The third is generated after the producer corrects its effective time from 10:00 to 10:10. If the event protocol has immutable IDs, the third should be flagged as a conflicting duplicate and the correction delivered with a new stable identity linked to the earlier event. If the protocol uses a mutable business key and separate source version, the correction must carry a higher version. An implementation that keeps whichever payload arrived last lets a network retry reverse a valid correction.

Fixture Independent expectation
Valid original ID at version 1 Publish one accepted availability change
Byte-equivalent retry with different transport metadata No second business change
Same ID and version, altered available flag Record conflict for producer owner
Higher valid revision with explicit supersession Apply correction according to materialization rules
Delayed first version after a correction Preserve receipt and do not replace the current result
Valid shape and unauthorized region for sender Reject from curated contract, route to owner safely

Choose how canonical representation affects equivalence. JSON object field order has no business meaning in typical JSON models. Two UTC representations can denote the same instant, while preservation of the original offset may matter for investigation. Hashing original bytes supports immutable audit. Hashing validated canonical fields supports content equivalence if the normalization policy is explicit. They serve different uses. If you reuse just one hash, be clear whether values with optional defaults or alternate order are treated as the same event. Keep evidence for both if exact byte audit and business comparison are required.

Manage invalid delivery and new fields

A fourth region may be added when a partner starts commercial operations. Older strict readers with a closed enum will reject the representation. A converter that maps an unknown region to UK silently corrupts tenancy and geography. Use a staged compatibility plan: inventory consumers, teach real regions where appropriate, test handling for unsupported consumers, then activate the producer. Keep older replay formats available or provide an authorized converter. Adding a field may be compatible with some readers and rejected by strict ones. Test the actual readers and contract version rather than using a general label like additive.

A quarantined receipt needs source identity, receipt time, failure classification, payload version and protected access to raw details. The application allows different audiences to view each part. Keep sensitive data out of generic alerts. If a valid correction is later authorized, track the original failure and the update, test against already-accepted earlier events, and release the repaired output through the same curated publication gate. Deleting the raw evidence makes replay and audit difficult. Untrusted data cannot be routed directly to downstream analytics without its normal protections.

Run a bilingual timestamp contract drill

Publish fixtures for a local offset near a seasonal boundary, an explicit equivalent UTC instant, a datetime without an offset, and a valid older event that arrives after the correction. Use the same validation suite for the two producer versions and one reader. List the expected canonical instant and business state for each. Check the first two have matching time semantics when intended, while the unspecified zone is rejected or follows a documented source rule. Replay the entire valid fixture set twice and verify a single current availability state per business key and complete receipt history per attempt. Report what selection predicate made the correction win and how the evidence would change if the provider authorized another region. Finish by distinguishing app validity, source ownership and transport behavior with one measurable expected result for each.

JSON Schema reference · Apache Beam schemas · AWS ingestion and transformation domain

Full curriculum

Menu

Student portal

Find a programme

Essential cookies

These keep you signed in and protect the forms you submit. Your browser also remembers whether you dismissed this notice.

Privacy and cookies